在本篇文章中,我们主要介绍注入参数的内容,自我感觉有个不错的建议和大家分享下
在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>