本文介绍了在Spring中在XML中使用Qualifier注释的替代方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring中,如果有两个引用相同类的bean id,而我们只想从一个bean中注入值,那么通常我们结合使用以下注释:

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")

如何使用xml规范实现相同的目的?在xml中使用限定符注释的替代方法是什么?

How to achieve the same thing using the xml specification ? What is the alternative of using qualifier annotation in xml ?

推荐答案

不是确切的替代方案,但是您可以对要排除在外的所有bean使用 autowire-candidate ="false" 与将要自动接线的电线分开进行自动接线.

另外,您还需要通过明确标记 primary ="true" primary ="false" 来指定适合自动装配的特定bean.

因此,当您希望自动连接 bean1
< bean id ="bean1" class ="xyzClassA"primary =" true"autowire-candidate =" true"/>< bean id ="bean2" class ="x.y.z.ClassA" primary ="false" autowire-candidate ="false"/>< bean id ="bean3" class ="xyzClassA" primary ="false" autowire-candidate ="false"/>

请注意,两个 autowire-candidate primary beans 标记的属性,默认值为 true .

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.

这篇关于在Spring中在XML中使用Qualifier注释的替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-19 01:40