Spring 2.5.6引见(五)——自动装载byName模式
Spring 2.5.6中自动装载byName模式
byName模式是根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。例如,在bean定义中将autowire设置为by name,而该bean包含master属性(同时提供setMaster(..)方法),Spring就会查找名为master
的bean定义,并用它来装配给master属性。
下面我来用一个实例来说明:
首先创建一个含有一个字符串属性address的类AddressServiceImpl
然后在创建一个含义AddressSerViceImp对象属性的类EmpServiceImpl并且实现get set 方法
Xml配置文件中:
package cn.****.service;
public class AddressServiceImpl {
private String address;
public void setAddress(String address) {
this.address = address;
}
}
package cn.****.service;
public class EmpServiceImpl {
private AddressServiceImpl addressServiceImpl ;//属性名必须跟xml文件的AddressServiceImp bean的id名一致
public EmpServiceImpl(){
}
public void setAddressServiceImpl(AddressServiceImpl addressServiceImpl) {
this.addressServiceImpl = addressServiceImpl;
}
public AddressServiceImpl getAddressServiceImpl() {
return addressServiceImpl;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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.0.xsd">
<bean id="addressServiceImpl" class="cn.****.service.AddressServiceImpl">
<property name="address">
<value>河北</value>
</property>
</bean>
<bean id="empServiceImpl" class="cn.****.service.EmpServiceImpl" scope="singleton" autowire="byName">
</bean>
</beans>