一、概述
DI(Dependency Injection)依賴注入,當前對象需要使用其他類的對象的時候,由spring提供,使用者只需要在配置文件中維護依賴關係即可,這種方式稱之爲依賴注入
二、三種類型的注入數據
1. String和基本類型
2. 其他bean類型(在spring配置文件中配置過或者註解配置過的bean)
3. 複雜類型/集合類型
<!--
複雜類型/集合注入:主要使用list和map標籤實現
屬性含義:
list:list,array,set類型的數據可以使用list標籤注入
map:map,property類型的數據可以使用map標籤注入
總結:結構相同,標籤可以互換
-->
<bean id="teacher" class="com.lizza.entity.Teacher">
<property name="students">
<list>
<value>張三</value>
<value>李四</value>
<value>王五</value>
</list>
</property>
<property name="info">
<map>
<entry key="name" value="李老師"/>
<entry key="age" value="19"/>
<entry key="sex" value="女"/>
</map>
</property>
</bean>
@Data
public class Teacher {
private List<String> students;
private Map<String, Object> info;
}
總結:結構相同,標籤可以互換
三、三種注入方式
1. 構造器注入
<!--
1. 構造器注入(基本類型和其他bean類型)
在bean標籤內部使用constructor-arg標籤
屬性:
name:構造器參數名
value:構造器參數值
ref:構造器引用類型參數名,如Data類型參數
type:構造器參數類型
index:構造器參數位置,從0開始
優勢:能夠保證注入的組件不可變,並且確保需要的依賴不爲空,保證完全初始化的狀態
弊端:增加了對象初始化時的複雜度
-->
<bean id="user" class="com.lizza.entity.User">
<constructor-arg name="name" value="栗子"/>
<constructor-arg name="age" value="18"/>
<constructor-arg name="birthday" ref="birthday"/>
</bean>
<bean id="birthday" class="java.util.Date"/>
public class User {
private String name;
private Integer age;
private Date birthday;
public User(String name, Integer age, Date birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
}
構造器注入的優勢和弊端:
- 優勢:能夠保證注入的組件不可變,並且確保需要的依賴不爲空,保證完全初始化的狀態
- 弊端:增加了對象初始化時的複雜度
2. set方法注入
<!--
set方法注入:在bean標籤中使用property屬性(更常用)
屬性含義:
name:構造器參數名
value:構造器參數值
ref:構造器引用類型參數名,如Data類型參數
優勢:降低了對象初始化時的複雜度
弊端:不能能夠保證注入的組件不可變,不能確保需要的依賴不爲空,不能保證完全初始化的狀態
-->
<bean id="student" class="com.lizza.entity.Student">
<property name="name" value="桃子"/>
<property name="age" value="18"/>
<property name="birthday" ref="birthday"/>
</bean>
@Data
public class Student {
private String name;
private Integer age;
private Date birthday;
}
set方法注入的優勢和弊端
- 優勢:降低了對象初始化時的複雜度
- 弊端:不能能夠保證注入的組件不可變,不能確保需要的依賴不爲空,不能保證完全初始化的狀態