简体   繁体   English

Spring @Autowire批注

[英]Spring @Autowire annotation

I have a question on Spring Autowire Annotation.The scenario is like this : Iam using @Autowire on class A and using it in 2 places -Class B and Class C like below: 我对Spring Autowire Annotation有一个疑问。场景是这样的:Iam在A类上使用@Autowire并在2个地方使用它-B类和C类,如下所示:

public class B 
{

@Autowired
private A a;
......

Map<String, Map<String,String>> map1=a.getNameValues();
Map<String, Map<String, String>> map2 = a.get("key");
if (map2!=null)
 map1.putAll(map2);

and also in other class C as shown below: 以及其他C类,如下所示:

public class C 
 {

@Autowired
private A a;
......

Map<String, Map<String,String>> map1=a.getNameValues();
Map<String, Map<String, String>> map2 = a.get("key");
if (map2!=null)
map1.putAll(map2);
 }

The program control flows from Class B to class C. So since the class A is autowired in both the places. 程序控制从B类流向C类。因此,由于A类在两个地方都自动接线。 so when the control comes first to class B ,map2 is retrieved and put in map1 . 因此,当控件首先进入类B时,将检索map2并将其放入map1中。 when the control comes to Class C , map1 already has map2 values. 当控件进入C类时,map1已经具有map2值。 What are the possible ways to control this kind of scenarios? 有什么方法可以控制这种情况? As i want both classes to work independently and use the Autowired class. 因为我希望两个类都可以独立工作并使用Autowired类。 Let me know your thoughts. 让我知道你的想法。

@Autowire will automagically inject a spring bean into the given property. @Autowire会自动将spring bean注入给定的属性。

It sounds like your question is actually related to the scope of the bean being injected. 听起来您的问题实际上与所注入的bean的范围有关。 So assuming your A class looks like this: 因此,假设您的A类如下所示:

@Component
public class A {
    ....
}

Then what will happen is spring will create a single instance (aka a Singleton) of A (in the given application context) and inject this into both B and C 然后会发生什么是春天将创建一个单一实例(又名一个Singleton) A (在给定应用程序上下文),并注入到这两个BC

Question - Is this the problem you are trying to solve? 问题 -这是您要解决的问题吗? When you say you want both classes to act independently you mean the fact that the A object in B and C are the exact same object? 当您说您希望两个类都独立运行时,是指BC中的A对象是完全相同的对象吗?

To get spring to wire a new instance of A you can simply change the scope of A to be prototype. 为了使弹簧连接A的新实例,您只需将A的范围更改为原型即可。

@Component
@Scope(value = "prototype")
public class A {
    ....
}  

or in xml 或在xml中

<bean id="a" class="A" scope="prototype"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM