Spring 自动装配

Scroll Down

定义people类

public class People {
    private Address address;
    private IdentityCard idcard;

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address_new) {
        this.address = address_new;
    }

    public IdentityCard getIdcard() {
        return idcard;
    }

    public void setIdcard(IdentityCard idcard) {
        this.idcard = idcard;
    }

    @Override
    public String toString() {
        return "People{" +
                "address=" + address+
                ", idcard=" + idcard +
                '}';
    }
}

无autowired

<bean id="people" class="com.buaoy.People">

运行结果
image.png

byName

    <bean id="address_new" class="com.buaoy.Address" c:province="浙江省" p:city="杭州市"/>
    <bean id="address" class="com.buaoy.Address" c:province="浙江省" p:city="温州市"/>
    <bean id="idcard1" class="com.buaoy.IdentityCard">
        <property name="id" value="12345678"/>
    </bean>

    <bean id="people" class="com.buaoy.People" autowire="byName"/>

运行结果
image.png
可见注入的是address_new的属性而不是address的属性,因为在set方法中Address的变量名为address_new

byType

    <bean id="address" class="com.buaoy.Address" c:province="浙江省" p:city="杭州市"/>

    <bean id="idcard1" class="com.buaoy.IdentityCard">
        <property name="id" value="12345678"/>
    </bean>

    <bean id="people" class="com.buaoy.People" autowire="byType"/>

运行结果
image.png
如果加多一行

<bean id="address-new" class="com.buaoy.Address" c:province="浙江省" p:city="温州市"/>

就会报错
image.png
因为byType方式在xml文件中只能实例化一种类,不能实例化多个

总结

autowired主要有三种选择,no、byName和byType。
no为默认方式,即不自动装配;
byName通过变量名从容器上下文寻找对应的对象,同一属性的对象只能有一个
byType通过类型从容器上下文寻找对应的对象,同一属性的对象只能有一个