# DI依賴注入環境-值注入
###### tags: `Spring-DI`
## 構造器注入


## Set方式注入(重點)
### 依賴注入:Set注入!
#### 依賴:bean對象的創建依賴於容器
#### 注入:bean對象中的所有屬性,由容器來注入
********
### 環境搭建
#### 1.複雜類型
```java=
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
```
#### 2.真實測試對象
```java=
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String ,String> card;
private Set<String> games;
private String wife;
private Properties info;
}
```
#### 3.beans.xml
```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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.kuang.pojo.Student">
<!--第一種:普通值注入,value-->
<property name="name" value="秦心"/>
</bean>
</beans>
```
#### 4.測試類
```java=
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student)context.getBean("student");
System.out.println(student.getName());
}
}
```
#### 5.完善注入信息
```xml=
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="西安"/>
</bean>
<bean id="student" class="com.kuang.pojo.Student">
<!--第一種:普通值注入(基本數據類型、String),value-->
<property name="name" value="秦心"/>
<!--第二種:bean注入,ref-->
<property name="address" ref="address"/>
<!--數組-->
<property name="books">
<array>
<value>紅樓夢</value>
<value>西遊記</value>
<value>三國演義</value>
</array>
</property>
<!--List-->
<property name="hobbys">
<list>
<value>聽歌</value>
<value>敲代碼</value>
<value>看電影</value>
</list>
</property>
<!--Map-->
<property name="card">
<map>
<entry key="身分證" value="123456"></entry>
<entry key="銀行卡" value="841245"></entry>
</map>
</property>
<!--Set -->
<property name="games">
<set>
<value>LOL</value>
<value>CSGO</value>
<value>ALEX</value>
</set>
</property>
<!--null-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="學號">123</prop>
<prop key="性別">男</prop>
<prop key="姓名">靈夢</prop>
</props>
</property>
</bean>
</beans>
```
```java=
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student)context.getBean("student");
System.out.println(student.toString());
//Student{
// name='秦心',
// address=Address{address='西安'},
// books=[紅樓夢, 西遊記, 三國演義],
// hobbys=[聽歌, 敲代碼, 看電影],
// card={身分證=123456, 銀行卡=841245},
// games=[LOL, CSGO, ALEX],
// wife='null',
// info={學號=123, 性別=男, 姓名=靈夢}}
}
}
```
