构造器注入:利用构造函数为对象中的属性注入值,需要在xml配置文件中进行手动的配置.
要求:
对象中必须存在有参数的构造函数.xml中手动配置了哪些属性需要注入值,对象中必须存在对应的属性为参数的构造函数.
如何配置:
需要为对象中的每个属性配置一个"constructor-arg"标签:
<constructor-arg name="" />
其中name属性的值构造函数中形参的名字.如何给属性注入值时,需要先确定该属性的类型(与setter注入方式类似)
对象中的属性分为以下三种类型,不同的类型使用不同的注入方式
1):简单数据类型(八大基本类型,String,BigDecimal,Date等). 使用value.
2):复合数据类型. 使用ref.
3):集合数据类型. 使用集合的元素.
小结:
1.构造器的注入方式与setter注入方式类型,配置文件只是把setter注入方式中的"property"标签替换为"constructor-arg"标签.
2.使用构造器注入方式,在xml配置文件中配置了要为哪些属性注入值,在对象中必须存在对应的所有属性的构造函数.
代码:
App-context.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.xsd">
<bean id="employee" class="text.spring._02_constructor.Employee">
<constructor-arg name="name" value="jack"/>
<constructor-arg name="age" value="18"/>
<constructor-arg name="birthday" value="2019/01/01"/>
<constructor-arg name="salary" value="1000.00"/>
</bean>
</beans>
App.java:
package text.spring._02_constructor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by thinkpad on 2019/9/3.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class App {
@Autowired
private Employee employee;
@Test
public void testEmployee() throws Exception {
System.out.println(employee);
}
}
Employee.java:
package text.spring._02_constructor;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by thinkpad on 2019/9/3.
*/
public class Employee {
private String name;
private Integer age;
private Date birthday;
private BigDecimal salary;
public Employee(String name, Integer age, Date birthday, BigDecimal salary) {
this.name = name;
this.age = age;
this.birthday = birthday;
this.salary = salary;
}
public Employee() {
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
", salary=" + salary +
'}';
}
}

本文介绍了Spring框架中的构造器注入机制,强调了在XML配置文件中如何手动配置以向对象属性传递值。内容涵盖了构造器注入的要求,包括对象需有参数的构造函数,以及在XML中配置`constructor-arg`标签的细节。根据属性类型,注入方式分为简单数据类型使用`value`,复合数据类型使用`ref`,集合数据类型使用集合元素。总结指出构造器注入与setter注入的相似性,并要求在对象中对应所有要注入的属性构造函数。
1285

被折叠的 条评论
为什么被折叠?



