每一個基於java的應用程式都有一個共同工作來展示給使用者看到的內容作為工作的應用幾個對象。當編寫一個複雜的Java應用程式,應用程式類應該儘可能獨立其他Java類來增加重複使用這些類,並獨立於其他類別的測試它們,而這樣做單元測試的可能性。依賴注入(或有時稱為布線)有助於粘合這些類在一起,同時保持他們的獨立。
考慮有其中有一個文字編輯器組件的應用程式,要提供拼字檢查。標準的代碼將看起來像這樣:
public class TextEditor { private SpellChecker spellChecker; public TextEditor() { spellChecker = new SpellChecker(); }}
我們在這裡所做的就是建立文本編輯和拼字檢查之間的依賴性。在控制方案中的反轉,我們反而會做這樣的事情:
public class TextEditor { private SpellChecker spellChecker; public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; }}
在這裡,文本編輯不應該擔心拼字檢查落實。拼字檢查器將獨立實施,將提供給文本編輯在文本編輯執行個體化的時候,這整個過程是由Spring架構的控制。
在這裡,我們已經刪除從文本編輯的全面控制,並保持它在其他地方(即XML設定檔)和依賴性(即類拼字檢查)被注入到類文本編輯通過類建構函式。因此,流程式控制制已經“倒”通過依賴注入(DI),因為已經有效地委派依賴一些外部系統。
依賴注入的第二種方法是通過文本編輯類,我們將建立拼字檢查執行個體的setter方法,該執行個體將被用來調用setter方法來初始化文本編輯的屬性。
因此,DI主要有兩種變體和下面的兩個子章將涵蓋兩者結合執行個體:
基於建構函式的依賴注入
當容器調用類的建構函式有多個參數,每個代表在其他類中的建構函式依賴關係為基礎的DI來完成。
例子:
下面的例子顯示了一個類文本編輯TextEditor 只能是依賴注入與建構函式注入。
我們使用Eclipse IDE,然後按照下面的步驟來建立一個Spring應用程式:
這裡是TextEditor.java檔案的內容:
package com.yiibai;public class TextEditor { private SpellChecker spellChecker; public TextEditor(SpellChecker spellChecker) { System.out.println("Inside TextEditor constructor." ); this.spellChecker = spellChecker; } public void spellCheck() { spellChecker.checkSpelling(); }}
下面是另外一個相關的類檔案SpellChecker.java內容:
package com.yiibai;public class SpellChecker { public SpellChecker(){ System.out.println("Inside SpellChecker constructor." ); } public void checkSpelling() { System.out.println("Inside checkSpelling." ); } }
以下是MainApp.java檔案的內容:
package com.yiibai;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); TextEditor te = (TextEditor) context.getBean("textEditor"); te.spellCheck(); }}
以下是設定檔beans.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 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Definition for textEditor bean --> <bean id="textEditor" class="com.yiibai.TextEditor"> <constructor-arg ref="spellChecker"/> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="com.yiibai.SpellChecker"> </bean></beans>
建立原始碼和bean設定檔完成後,讓我們運行應用程式。如果一切順利將列印以下資訊:
Inside SpellChecker constructor.Inside TextEditor constructor.Inside checkSpelling.
建構函式的參數解析:
可能有歧義存在,而將參數傳遞給建構函式的情況下有一個以上的參數。要解決這種不確定性,其中的構造器參數在一個bean定義中定義的順序就是這些參數提供給適當的建構函式的順序。請考慮下面的類:
package x.y;public class Foo { public Foo(Bar bar, Baz baz) { // ... }}
下面的配置工作正常:
<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>
讓我們檢查一個更多情況下我們通過不同類型的建構函式。請考慮下面的類:
package x.y;public class Foo { public Foo(int year, String name) { // ... }}
容器也可以使用類型匹配與簡單類型,如果你明確地指定使用type屬性的建構函式的參數類型。例如:
<beans> <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg type="int" value="2001"/> <constructor-arg type="java.lang.String" value="Zara"/> </bean></beans>
最後,並通過建構函式參數的最佳方法,使用索引屬性來顯式地指定一個構造器參數的索引。這裡的索引是從0開始。例如:
<beans> <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="2001"/> <constructor-arg index="1" value="Zara"/> </bean></beans>
最後需要說明的,如果你傳遞一個引用到一個對象,需要使用<constructor-arg>標籤的ref屬性,如果是直接傳遞一個值,那麼應該使用value屬性。
基於setter方法的依賴注入
基於setter DI由容器調用setter方法對bean調用無參構造器或無參staticFactory 方法執行個體化bean之後完成。
這裡是TextEditor.java檔案的內容:
package com.yiibai;public class TextEditor { private SpellChecker spellChecker; // a setter method to inject the dependency. public void setSpellChecker(SpellChecker spellChecker) { System.out.println("Inside setSpellChecker." ); this.spellChecker = spellChecker; } // a getter method to return spellChecker public SpellChecker getSpellChecker() { return spellChecker; } public void spellCheck() { spellChecker.checkSpelling(); }}
在這裡,需要檢查setter方法的命名規範。設定我們使用setSpellChecker()方法,這是非常類似於Java POJO類的變數的拼字檢查器。讓我們創造另一個相關的類檔案SpellChecker.java,內容如下:
package com.yiibai;public class SpellChecker { public SpellChecker(){ System.out.println("Inside SpellChecker constructor." ); } public void checkSpelling() { System.out.println("Inside checkSpelling." ); } }
以下是MainApp.java檔案的內容:
package com.yiibai;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); TextEditor te = (TextEditor) context.getBean("textEditor"); te.spellCheck(); }}
以下是設定檔beans.xml檔案裡面有配置為基於setter方法注入:
<?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 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Definition for textEditor bean --> <bean id="textEditor" class="com.yiibai.TextEditor"> <property name="spellChecker" ref="spellChecker"/> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="com.yiibai.SpellChecker"> </bean></beans>
應該注意在基於建構函式注入和setter注入定義beans.xml檔案的差異。唯一的區別是,我們已經使用<constructor-arg>標籤為基於建構函式的注入和的<property>標籤為基於setter注入的<bean>元素內。
需要注意的第二個重要的一點是,如果傳遞一個引用到一個對象,需要使用<property>標籤的ref屬性,如果是直接傳遞一個值,那麼應該使用value屬性。
建立原始碼和bean設定檔完成後,讓我們運行應用程式。如果一切順利,這將列印以下資訊:
Inside SpellChecker constructor.Inside setSpellChecker.Inside checkSpelling.
採用p名稱空間的XML配置:
如果你有很多的setter方法則可以很方便地使用p名稱空間的XML設定檔中。讓我們查看他們的區別:
讓我們來用的<property>標籤標準的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 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="john-classic" class="com.example.Person"> <property name="name" value="John Doe"/> <property name="spouse" ref="jane"/> </bean> <bean name="jane" class="com.example.Person"> <property name="name" value="John Doe"/> </bean></beans>
上面的XML配置可重寫使用 p-namespace如下一個簡潔的方法:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="john-classic" class="com.example.Person" p:name="John Doe" p:spouse-ref="jane"/> </bean> <bean name="jane" class="com.example.Person" p:name="John Doe"/> </bean></beans>
在這裡,不應該在指定原始值和對空間對象引用的區別。-ref部分表示,這不是直鏈的值,而是一個引用到另一個bean中。