What is the alternative of using Qualifier annotation in XML in Spring?

拈花ヽ惹草 提交于 2021-02-08 08:17:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!