在Spring中,@ Qualifier表示哪个bean有资格在字段上自动装配。 请参阅以下场景:
自动接线示例
参见下面的示例,它将自动将“ person” bean连线到客户的person属性中。
package com.mkyong.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer {
@Autowired
private Person person;
//...
}
但是,在bean配置文件中声明了两个类似的bean“ com.mkyong.common.Person
”。 Spring会知道应该自动连接哪个人的bean?
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="customer" class="com.mkyong.common.Customer" />
<bean id="personA" class="com.mkyong.common.Person" >
<property name="name" value="mkyongA" />
</bean>
<bean id="personB" class="com.mkyong.common.Person" >
<property name="name" value="mkyongB" />
</bean>
</beans>
在上面的示例中运行时,它会在下面的异常中命中:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.mkyong.common.Person] is defined:
expected single matching bean but found 2: [personA, personB]
@Qualifier示例
要解决上述问题,您需要@Quanlifier告诉Spring应该自动装配哪个bean。
package com.mkyong.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer {
@Autowired
@Qualifier("personA")
private Person person;
//...
}
在这种情况下,bean“ personA”是自动装配的。
Customer [person=Person [name=mkyongA]]
下载源代码
下载它– Spring-AutoWiring-Qualifier-Example.zip (6 KB)
参考
翻译自: https://mkyong.com/spring/spring-autowiring-qualifier-example/