@Qualifier注解意味着可以在被标注bean的字段上可以自动装配。Qualifier注解可以用来取消Spring不能取消的bean应用。
下面的示例将会在Customer的person属性中自动装配person的值。
|
1
2
3
4
5
|
public class Customer{ @Autowired private Person person;} |
下面我们要在配置文件中来配置Person类。
|
1
2
3
4
5
6
7
8
9
|
<bean id="customer" class="com.howtodoinjava.common.Customer" /><bean id="personA" class="com.howtodoinjava.common.Person" > <property name="name" value="lokesh" /></bean><bean id="personB" class="com.howtodoinjava.common.Person" > <property name="name" value="alex" /></bean> |
Spring会知道要自动装配哪个person bean么?不会的,但是运行上面的示例时,会抛出下面的异常:
|
1
2
3
|
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.howtodoinjava.common.Person] is defined: expected single matching bean but found 2: [personA, personB] |
要解决上面的问题,需要使用 @Quanlifier注解来告诉Spring容器要装配哪个bean:
|
1
2
3
4
5
6
|
public class Customer{ @Autowired @Qualifier("personA") private Person person;}
|