本文連接:http://www.lxweimin.com/p/df19a9ec8268
本文作者:gks09@qq.com
什么是依賴注入?
依賴注入(DI)是指對象定義它們自身依賴的過程。此過程可以通過配置構造方法的參數來定義依賴,也可以通過配置工廠方法的參數來獲得依賴,還可以在對象實例化后配置屬性來定義依賴。
Dependency injection (DI) is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean.
——Spring官方文檔7.4.1 Dependency Injection
一般來說我們所需要的對象(可以是POJO,也可以不是POJO)會有諸多依賴(例如一個User對象有name、sex等屬性,一個query服務對象依賴于數據庫連接管理對象等),不使用Spring框架的時候,我們會在代碼中使用new關鍵字來產生新對象;使用Spring框架后,可以通過xml配置、Java代碼配置等方式,直接產生新對象并交由Spring框架(IoC container)統一管理。
原先對所有對象的控制權在于我們,我們在代碼邏輯中控制對象;現在所有的對象配置好后,在項目執行階段就完全交由Spring框架管理,包括對象的實例化、對象銷毀、多個對象之間相互依賴等。這就是控制反轉(Inversion of Control,IOC)。
參考:1、Spring官方文檔(7. The IoC container)
依賴注入的優缺點?
優點
DI是一種編程思想,其目的是統一的對象和依賴管理。DI的優點是會更易于管理和解耦對象之間的依賴,使得代碼更加的簡單。對象不再關注依賴,也不需要知道依賴類的位置。這樣的話,開發者的類更加易于測試,尤其是當開發者的依賴是接口或者抽象類的情況,開發者可以輕易在單元測試中mock對象。
Code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies, and does not know the location or class of the dependencies. As such, your classes become easier to test, in particular when the dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations to be used in unit tests.
——Spring官方文檔7.4.1 Dependency Injection
缺點
從Stack Overflow上,看到一些討論,獲得認同最多的回答如下:
A couple of points:
DI increases complexity, usually by increasing the number of classes since responsibilities are separated more, which is not always beneficial
Your code will be (somewhat) coupled to the dependency injection framework you use (or more generally how you decide to implement the DI pattern)
DI containers or approaches that perform type resolving generally incur a slight runtime penalty (very negligible, but it's there)
Generally, the benefit of decoupling makes each task simpler to read and understand, but increases the complexity of orchestrating the more complex tasks.
——What are the downsides to using Dependency Injection? [closed]
Stack Overflow的答者認為:
依賴注入增加了復雜度。有時候為了將不同對象的責任完全劃分,會增加對象(類)的數量,并非總是有益。
代碼可能會和依賴注入框架耦合。
依賴注入容器或實現方法需要進行類型解析,會帶來輕微的不足。
目前筆者個人不太能深入理解依賴注入的缺點。個人認為,依賴注入會增加代碼量(但好的DI框架可以幫助我們減少代碼),在項目開始前需要對不同對象、不同業務進行劃分,對開發者有一定的要求。
當然依賴注入的缺點,本身就是一個有爭議的話題。沒有一種pattern是完美的。
參考:1、What are the downsides to using Dependency Injection? [closed]
結合Spring框架談DI
結合Spring Framework談一談依賴注入,Spring Framework做了很多工作,避免依賴注入和業務代碼耦合,有助于我們專注于對象、依賴、業務的設計。Spring幫助我們產生、管理、使用、銷毀bean,不需要我們手動去操作bean。不過帶來的缺點就是Spring框架較為復雜,上手慢,用得不好會適得其反。
Spring的依賴注入方式
本節主要引用Spring官方文檔。
基于構造方法的注入
基于構造函數的依賴注入是由IoC容器來調用類的構造函數,構造函數的參數代表這個Bean所依賴的對象。跟調用帶參數的靜態工廠方法基本一樣。下面的例子展示了一個類通過構造函數來實現依賴注入的。
package x.y;
public class Foo {
public Foo(Bar bar, Baz baz) {
// ...
}
}
xml的配置如下:
<beans>
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
</bean>
<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
</beans>
另外,bean的參數為簡單類型時(如Java基本類型、String等),可以使用type
字段進行配置:
package examples;
public class ExampleBean {
// Number of years to calculate the Ultimate Answer
private int years;
// The Answer to Life, the Universe, and Everything
private String ultimateAnswer;
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
也可以使用index
字段進行配置,指明構造函數的參數index:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>
同樣,也可以使用參數名進行配置:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg name="years" value="7500000"/>
<constructor-arg name="ultimateAnswer" value="42"/>
</bean>
需要注意的是,做這項工作的代碼必須啟用了調試標記編譯,這樣Spring才可以從構造函數查找參數名稱。開發者也可以使用@ConstructorProperties注解來顯式聲明構造函數的名稱,比如如下代碼:
package examples;
public class ExampleBean {
// Fields omitted
@ConstructorProperties({"years", "ultimateAnswer"})
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
基于setter方法的注入
基于setter函數的依賴注入則是容器會調用Bean的無參構造方法,或者無參數的工廠方法,然后再來調用setter方法來實現的依賴注入。有的時候,會有對象相互依賴的情況,如A依賴B、B也依賴A。這時候無法通過含參的構造方法來注入A和B,需要先調用無參構造方法,然后用過Setter設置屬性。
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne;
}
public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo;
}
public void setIntegerProperty(int i) {
this.i = i;
}
}
<bean id="exampleBean" class="examples.ExampleBean">
<!-- setter injection using the nested ref element -->
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
<!-- setter injection using the neater ref attribute -->
<property name="beanTwo" ref="yetAnotherBean"/>
<property name="integerProperty" value="1"/>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
ApplicationContext所管理Bean對于基于構造函數的依賴注入,或者基于Setter方式的依賴注入都是支持的。同時也支持使用setter方式在通過構造函數注入依賴之后再次注入依賴。開發者在BeanDefinition中可以使用PropertyEditor實例來自由選擇注入的方式。然而,大多數的開發者并不直接使用這些類,而是跟喜歡XML形式的bean定義,或者基于注解的組件(比如使用
@Component
,@Controller
等)或者在配置了@Configuration
的類上面使用@Bean
的方法。
本質上,使用annotation進行也是使用基于構造方法的注入或基于setter的注入。
如何選擇注入方式?
一般來說,我們可以混用基于構造方法的注入和基于setter的注入。Spring建議我們,使用constructor-based dependency injection進行強制依賴的注入,使用setter-based dependency injection 進行可選依賴的注入。當然,可以在Setter方法上面的@Required
注解可用來構造必要的依賴。
Constructor-based dependency injection有幾點好處:它可以保證注入的依賴是非null
的,并且該組件被他人調用時一定是完好的。此外要注意,構造方法不應有過多參數,參數過多說明該對象的功能過復雜,應考慮拆分。
Setter-based dependency injection的好處是,可以進行重配置和重新注入。Setter-based dependency injection應給對象的屬性附初始值,否則在使用時需要進行非null
檢查。
依賴注入的解析過程
Spring容器首先會實例化ApplicationContext,然后依據xml、annotation或java代碼進行bean的加載。如果bean依賴于其他bean,則依賴的bean會先加載。
在容器創建后,容器會驗證bean的配置,但是bean的屬性沒有被賦值。單例類型的bean會先預實例化(pre-instantiated)。bean只有被請求時,才會真正創建。
創建bean時,實際上是創建了一個依賴圖,容器按此順序進行bean的創建。
依賴注入的實現方法
待補充