Spring按名称自动装配--byName

在Spring中,“按名称自动装配”是指,如果一个bean的名称与其他bean属性的名称是一样的,那么将自动装配它。
例如,如果“customer” bean公开一个“address”属性,Spring会找到“address” bean在当前容器中,并自动装配。如果没有匹配找到,那么什么也不做。
 
package auto_byname;

/**
 * Created by luozhitao on 2017/8/8.
 */
public class Customer {
    public Address getAddress() {
        return address;
    }

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

    private Address address;

}

 

package auto_byname;

/**
 * Created by luozhitao on 2017/8/8.
 */
public class Address {

    public String getAddress() {
        return address;
    }

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

    private  String address;
}

这里Customer的属性address和id=“address”名称相同,从而被装配

<bean id="address" class="auto_byname.Address">
        <property name="address" value="beijing"></property>
    </bean>
    <bean id="customer" class="auto_byname.Customer" autowire="byName"></bean>

 

posted on 2017-08-08 23:35  猫儿爹  阅读(284)  评论(0编辑  收藏  举报

导航