Spring Framework的一些思考——依賴注入

本文連接: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:

  1. DI increases complexity, usually by increasing the number of classes since responsibilities are separated more, which is not always beneficial

  2. Your code will be (somewhat) coupled to the dependency injection framework you use (or more generally how you decide to implement the DI pattern)

  3. 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的答者認為:

  1. 依賴注入增加了復雜度。有時候為了將不同對象的責任完全劃分,會增加對象(類)的數量,并非總是有益。

  2. 代碼可能會和依賴注入框架耦合。

  3. 依賴注入容器或實現方法需要進行類型解析,會帶來輕微的不足。

目前筆者個人不太能深入理解依賴注入的缺點。個人認為,依賴注入會增加代碼量(但好的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的創建。

依賴注入的實現方法


待補充

參考文檔:


  1. Dependencies

  2. Spring官方文檔[7.4.1 Dependency Injection]

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,739評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,634評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,653評論 0 377
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,063評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,835評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,235評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,315評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,459評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,000評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,819評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,004評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,560評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,257評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,676評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,937評論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,717評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,003評論 2 374