Spring的DI,即依赖注入,个人理解,就是给属性赋值。概念性的东西,不多说了。需要项目代码,点这里。
Spring给属性赋值,有2种方式,一是通过有参构造函数,二是通过set方法。
1.实体类:有两个构造函数
public class Person {
private String id;
private String name;
private Integer age;
public Person(){
System.out.println("无参构造函数,开始创建Person对象了。。。");
}
public Person(String id, String name, Integer age) {
System.out.println("利用有参构造函数,给属性赋值: id="+id+" name="+name+" age="+age);
this.id = id;
this.name = name;
this.age = age;
}
//省略set、get、toString方法
}
2.通过有参构造函数给属性赋值
在配置文件中,添加如下配置:
<!--给属性赋值的方法1:利用有参构造方法,其中:
index: 参数下标,表示第几个参数,从0开始
name:是属性名,
value:属性值(简单数据类型)
ref: 属性值(对象数据类型)
type: 参数类型
-->
<bean id="person1" class="com.qxf.pojo.Person">
<constructor-arg index="0" value="001"></constructor-arg>
<constructor-arg index="1" value="张三"></constructor-arg>
<constructor-arg index="2" value="21"></constructor-arg>
</bean>
3.通过set方法给属性赋值
在配置文件中,添加如下配置:
<!--给属性赋值的方法2:利用set方法,其中:
property:是属性名,
value:属性值(简单数据类型)
ref: 属性值(对象数据类型)
-->
<bean id="person2" class="com.qxf.pojo.Person">
<property name="id" value="002"></property>
<property name="name" value="李四"></property>
<property name="age" value="22"></property>
</bean>
完整配置文件如下:
<?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">
<!--给属性赋值的方法1:利用有参构造方法,其中:
index: 参数下标,表示第几个参数,从0开始
name:是属性名,
value:属性值(简单数据类型)
ref: 属性值(对象数据类型)
type: 参数类型
-->
<bean id="person1" class="com.qxf.pojo.Person">
<constructor-arg index="0" value="001"></constructor-arg>
<constructor-arg index="1" value="张三"></constructor-arg>
<constructor-arg index="2" value="21"></constructor-arg>
</bean>
<!--给属性赋值的方法2:利用set方法,其中:
property:是属性名,
value:属性值(简单数据类型)
ref: 属性值(对象数据类型)
-->
<bean id="person2" class="com.qxf.pojo.Person">
<property name="id" value="002"></property>
<property name="name" value="李四"></property>
<property name="age" value="22"></property>
</bean>
</beans>
4.测试
(1)测试代码
public class DITest {
public static void main(String[] args) {
//加载配置文件,启动容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//从容器中获取bean
Person person1 = context.getBean("person1", Person.class);
Person person2 = context.getBean("person2", Person.class);
System.out.println("通过参数构造函数注入属性值:"+person1);
System.out.println("通过set方法注入属性值:"+person2);
//关闭容器
context.close();
}
}
(2)测试结果
这下,就可以看到,对象的属性,都有值了,不再是null了