依賴注入 概述
控製反轉: 一般分為兩種類型,依賴注入(Dependency Injection,簡稱DI)和依賴查找(Dependency Lookup)。依賴注入:一種設計模式。一個類對另一個類有依賴時,由容器自動注入。
以下內容來自百度知道
假設你編寫了兩個類,一個是人(Person),一個是手機(Mobile)。
人有時候需要用手機打電話,需要用到手機的dialUp方法。
傳統的寫法是這樣:
public class Person{
public boolean makeCall(long number){
Mobile mobile=new Mobile();
return mobile.dialUp(number);
}
}
也就是說,類Person的makeCall方法對Mobile類具有依賴,必須手動生成一個新的實例new Mobile()才可以進行之後的工作。
依賴注入的思想是這樣,當一個類(Person)對另一個類(Mobile)有依賴時,不再該類(Person)內部對依賴的類(Moblile)進行實例化,而是之前配置一個beans.xml,告訴容器所依賴的類(Mobile),在實例化該類(Person)時,容器自動注入一個所依賴的類(Mobile)的實例。
依賴注入寫法是這樣:
public Interface MobileInterface{
public boolean dialUp(long number);
}
Person類:
public class Person{
private MobileInterface mobileInterface;
public boolean makeCall(long number){
return this.mobileInterface.dialUp(number);
}
public void setMobileInterface(MobileInterface mobileInterface){
this.mobileInterface=mobileInterface;
}
}
<bean >
<property name="mobileInterface">
<ref local="mobileInterface"/>
</property>
</bean>
<bean />
最後更新:2017-04-03 05:40:19