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>