自动装配示例
自动装配“person” bean 到 customer 的 person 属性
package com.yiibai.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer {
@Autowired
private Person person;
//...
}
xml
<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.yiibai.common.Customer" />
<bean id="personA" class="com.yiibai.common.Person" >
<property name="name" value="yiibaiA" />
</bean>
<bean id="personB" class="com.yiibai.common.Person" >
<property name="name" value="yiibaiB" />
</bean>
</beans>
异常
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.yiibai.common.Person] is defined:
expected single matching bean but found 2: [personA, personB]
@Qualifier示例
package com.yiibai.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer {
@Autowired
@Qualifier("personA")
private Person person;
//...
}