转载自:http://www.bianceng.cn/Programming/Java/201307/37027.htm
spring 装配Bean中构造参数的注入
spring装配bean中还有一种Set注入的替代,那就是构造参数的注入。
set注入是一种直接方式,缺点是它假设了 所 有的可变属性都可以通过set方法访问到。例如有些属性在创建时设置一次,以后不再改变。替代方式是通过构造函数设 置一些属性值。还有它无法清晰表达哪些属性是必须的,哪些是可选的,构造注入的优势是通过构造强制依赖关系,不可能 实例化不完全的或无法使用的bean。下面是构造器的几种注入方式:
1.通过构造函数注入 (原始方式)
2.根 据构造器参数的类型
3.根据索引index注入
4.根据参数名称注入
EmployeeBean.java
package www.csdn.spring.constructor.bean; public class EmployeeBean { private String name; private Double salary; private Dept dept; private String sex; // 构造器函数 public EmployeeBean(String name, Double salary, Dept dept, String sex) { super(); this.name = name; this.salary = salary; this.dept = dept; this.sex = sex; } @Override public String toString() { return "EmployeeBean [name=" + name + ", salary=" + salary + ", dept=" + dept + ", sex=" + sex + "]"; } }
Dept.java
package www.csdn.spring.constructor.bean; public class Dept { private String name; private String deptno; public void setName(String name) { this.name = name; } public void setDeptno(String deptno) { this.deptno = deptno; } @Override public String toString() { return "Dept [name=" + name + ", deptno=" + deptno + "]"; } }
spring-constructor.java
<?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.xsd"> <!-- private String name; private Double salary; private Dept dept; --> <!-- 0、通过构造函数注入 (原始方式)--> <!-- <bean id="employeeBean" class="www.csdn.spring.constructor.bean.EmployeeBean"> <constructor-arg value="王晓而" /> <constructor-arg value="100.0" /> <constructor-arg ref="dept" /> <constructor-arg value="男" /> </bean> --> <!-- 下面三种解决1存在的问题 --> <!-- 1、根据构造器参数的类型 --> <bean id="employeeBean" class="www.csdn.spring.constructor.bean.EmployeeBean"> <constructor-arg type="java.lang.String" value="陈红均" /> <constructor-arg type="java.lang.String" value="男" /> <constructor-arg type="java.lang.Double" value="100.0" /> <constructor-arg type="www.csdn.spring.constructor.bean.Dept" ref="dept" /> </bean> <!-- 2、根据索引index注入 --> <!-- <bean id="employeeBean" class="www.csdn.spring.constructor.bean.EmployeeBean"> <constructor-arg index="0" value="陈红均" /> <constructor-arg index="1" value="100.0" /> <constructor-arg index="2" ref="dept" /> <constructor-arg index="3" value="女" /> </bean> --> <!-- 3、根据参数名称注入 --> <!-- <bean id="employeeBean" class="www.csdn.spring.constructor.bean.EmployeeBean"> <constructor-arg name="name" value="陈红均" /> <constructor-arg name="salary" value="100.0" /> <constructor-arg name="dept" ref="dept" /> <constructor-arg name="sex" value="男" /> </bean>--> <bean id="dept" class="www.csdn.spring.constructor.bean.Dept"> <property name="name" value="CSDN教育事业部" /> <property name="deptno" value="0x0001" /> </bean> </beans>