Spring-configuration: I have created 2 beans with reference to same class but different database sessions.
<bean id="abc1" class="abc">
<bean id="abc2" class="abc">
Now is there any way to set bean with id "abc1" as default bean for autowiring and use abc2 for autowiring when mentioned explicitly like this:
@Autowiring
@Qualifier("abc2")
private abc obj;
Solution:
<bean id="abc1" class="abc" primary="true">
makes abc1 default one to be autowired.
for creating an instance of abc2, we can use this:
@Autowired
@Qualifier("abc2")
private abc obj;
The @primary
annotation or primary
attribute of xml is used exactly for that purpose. Here is the details of the same. It is pretty well documented here.
So if you mention <bean id="abc1" class="abc" primary="true"/>
it will get priority over abc2
, and you can use @Qualifier
for abc2
wherever you need. Hope this helps.
If you skip the @Qualifier
annotation, then Spring will lookup for a bean with the same name as the private
member. For example:
@Autowired
private abc abc1; //Spring will search for a bean with id="abc1"
This was you can use abc1
as a default value.
If you don't want to make Spring search for a specific bean, then you can trigger the @Qualifier
and then Spring will not care how the member is called, but will assign it's value to refer to the bean that has the same id
pointed out in the @Qualifier
annotation:
@Autowired
@Qualifier("abc2")
private abc theNameDoesNotMatter;
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.