自动装配示例

    1. 自动装配“person bean customer person 属性
    2. package com.yiibai.common;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.beans.factory.annotation.Qualifier;
    5. public class Customer {
    6. @Autowired
    7. private Person person;
    8. //...
    9. }

    xml

    1. <beans xmlns="http://www.springframework.org/schema/beans"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://www.springframework.org/schema/beans
    4. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    5. <bean
    6. class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    7. <bean id="customer" class="com.yiibai.common.Customer" />
    8. <bean id="personA" class="com.yiibai.common.Person" >
    9. <property name="name" value="yiibaiA" />
    10. </bean>
    11. <bean id="personB" class="com.yiibai.common.Person" >
    12. <property name="name" value="yiibaiB" />
    13. </bean>
    14. </beans>

    异常

    1. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
    2. No unique bean of type [com.yiibai.common.Person] is defined:
    3. expected single matching bean but found 2: [personA, personB]

    @Qualifier示例

    1. package com.yiibai.common;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.beans.factory.annotation.Qualifier;
    4. public class Customer {
    5. @Autowired
    6. @Qualifier("personA")
    7. private Person person;
    8. //...
    9. }