bytype模式:
如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配。如果存在多个该类型的bean,那么将会抛出异常,并指出不能使用byType方式进行自动装配。若没有找到相匹配的bean,则什么事都不发生,属性也不会被设置。如果你不希望这样,那么可以通过设置dependency-check="objects"让Spring抛出异常。
下面我来用一个实例来说明:
首先创建一个含有一个字符串属性address的类
AddressServiceImpl
package cn.csdn.service;
public class AddressServiceImpl {
private String address;
public void setAddress(String address) {
this.address = address;
}
}
然后在创建一个含义AddressSerViceImp对象属性的类EmpServiceImpl并且实现get set 方法
ackage cn.csdn.service;
public class EmpServiceImpl {
private AddressServiceImpl addressServiceImpl ;//属性名必须跟xml文件的AddressServiceImp bean的类型名一致
public EmpServiceImpl(){
}
public void setAddressServiceImpl(AddressServiceImpl addressServiceImpl) {
this.addressServiceImpl = addressServiceImpl;
}
public AddressServiceImpl getAddressServiceImpl() {
return addressServiceImpl;
}
}
Xml配置文件中:
<?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.csdn.service.AddressServiceImpl">
<property name="address">
<value>河北</value>
</property>
</bean>
<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl" scope="singleton" autowire="byName">
</bean>
</beans>