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了