1. 什么是注入
????????注入(Injection)表示的意思是通過Spring工廠及配置文件,為所創(chuàng)建的對象成員變量賦值。為什么需要注入,可以通過以下代碼來引出:
Person p = new Person();
// p對象的屬性值硬編碼在代碼中
p.setId(123456);
p.setName("Tom");
????????通過硬編碼賦值p對象的屬性,會(huì)造成耦合,這充分驗(yàn)證了一句話“需要就是依賴,依賴就會(huì)存在耦合”。為了處理這種耦合,Spring提供了一種方式,通過配置文件注入屬性的值,這樣屬性的取值就不會(huì)硬編碼在代碼中,更改屬性的值只需要改配置文件即可。
????????注入屬性的開發(fā)步驟可以是以下幾步,最終可以把屬性的賦值交由Spring進(jìn)行管理。
1. 定義類時(shí),為類的成員屬性,提供屬性的get set方法
class Person {
priavte String id;
private String name;
set;
get;
}
2. 通過Spring配置文件進(jìn)行注入配置
<bean id = "p" class = "x.x.Person">
<property name = "id">
<value>12345</vaule>
</property>
<property name = "name">
<value>Tom</vaule>
</property>
</bean>
上述復(fù)制的方式等效于
p.setId("123456")
p.setName("Tom");
????????可以看到通過把屬性提取到配置文件中配置,可以解耦合。其實(shí),在底層,Spring就是調(diào)用的屬性的set訪問來賦值。所以我們稱這種注入叫做set注入。
2. Spring創(chuàng)建對象的方式
????????Spring創(chuàng)建對象有三種方式:
1. 反射模式
2. 工廠方法模式
3. Factory Bean模式
2.1. 反射模式
????????反射模式創(chuàng)建對象,就是我們熟知的,使用<bean class="xx">標(biāo)簽,使用該標(biāo)簽,Spring則會(huì)使用反射創(chuàng)建該對象。這里我們可以討論兩個(gè)細(xì)節(jié),分別是無參構(gòu)造的類,有參構(gòu)造的類使用Spring該怎么創(chuàng)建對象。
public class Person {
public Person() {}
public Person(String name) {}
}
// 1. 無參構(gòu)造創(chuàng)建對象
<bean id="p" class="Person"/>
// 2. 有參構(gòu)造創(chuàng)建對象
<bean id="p" class="Person">
<constructor-arg name="name" value="Tom"/>
</bean>
2.2. 工廠方法模式
????????工廠方法模式中,Spring不會(huì)直接利用反射機(jī)制創(chuàng)建bean對象, 而是會(huì)利用反射機(jī)制先找到Factory類,然后利用Factory再去生成bean對象。工廠方法模式可以分為兩類,分別是靜態(tài)工廠方法模式,和實(shí)例工廠方法模式。
????????靜態(tài)工廠方法模式:
public class Person {
}
// 靜態(tài)工廠方法模式
public class PersonFactory {
private static Person p;
static {
p = new Person();
}
public static Person getPerson() {
return p;
}
}
<bean id="person" class="PersonFactory" factory-method="getPerson"/>
動(dòng)態(tài)方法工廠模式:
// 動(dòng)態(tài)工廠方法模式
public class PersonFactory {
private Person p = new Person();
public Person getPerson() {
return p;
}
}
<bean id="factory" class="PersonFactory"/>
<bean id="person" factory-bean="factory" factory-method="getPerson" />