问题
In Spring , if there are two bean ids which refer to the same class and we just want to inject values from only one bean, then we normally use the following annotations in conjunction :
@Autowired
@Qualifier("bean1")
How to achieve the same thing using the xml specification ? What is the alternative of using qualifier annotation in xml ?
回答1:
Not an exact alternative but you can use autowire-candidate="false"
to all those beans which you want to exclude from being autowired apart from the one which is to be autowired.
Also you need to specify that particular bean which is eligible for autowiring by explicitly marking primary="true"
for it and primary="false"
for rest of them.
So roughly your xml configuration should look like below when you expect bean1
to be autowired<bean id="bean1" class="x.y.z.ClassA" primary="true" autowire-candidate="true"/>
<bean id="bean2" class="x.y.z.ClassA" primary="false" autowire-candidate="false"/>
<bean id="bean3" class="x.y.z.ClassA" primary="false" autowire-candidate="false"/>
Do note that both autowire-candidate
and primary
are properties for beans
tag and has default value as true
.
来源:https://stackoverflow.com/questions/27058447/what-is-the-alternative-of-using-qualifier-annotation-in-xml-in-spring