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:
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:
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. so when the control comes first to class B ,map2 is retrieved and put in map1 . when the control comes to Class C , map1 already has map2 values. What are the possible ways to control this kind of scenarios? As i want both classes to work independently and use the Autowired class. Let me know your thoughts.
@Autowire will automagically inject a spring bean into the given property.
It sounds like your question is actually related to the scope of the bean being injected. So assuming your A
class looks like this:
@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
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?
To get spring to wire a new instance of A
you can simply change the scope of A
to be prototype.
@Component
@Scope(value = "prototype")
public class A {
....
}
or in xml
<bean id="a" class="A" scope="prototype"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.