Spring自动装载constructo模式
与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常
下面我来用一个实例来说明:
首先创建一个含有一个字符串属性address的类AddressServiceImpl
package cn.csdn.service;
public class AddressServiceImpl {
private String address;
public void setAddress(String address) {
this.address = address;
}
}
然后在创建一个含义AddressSerViceImp对象属性的类EmpServiceImpl并且实现带有参数的构造方法
package cn.csdn.service;
public class EmpServiceImpl {
private AddressServiceImpl addressServiceImpl ;
public EmpServiceImpl(AddressServiceImpl addressServiceImp){
this.addressServiceImpl = 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="constructo "> </bean> </beans>