依存注入とは


人間(Person)と携帯電話(Mobile)の2つのクラスを作成したとします.
人は時々携帯電話で電話をかける必要があり、携帯電話のdialUp方法を使う必要がある.
伝統的な書き方はこうです.
Java code

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;
    }
}



xmlファイルでの依存関係の構成
<bean id="person" class="Person">
    <property name="mobileInterface">
        <ref local="mobileInterface"/>
    </property>    
</bean>
<bean id="mobileInterface" class="Mobile"/>


このように、Personクラスは、電話をかけることを実現する際に、Mobileクラスの存在を知らず、1つのインタフェースMobileInterfaceを呼び出すことしか知らず、MobileInterfaceの具体的な実現はMobileクラスを通じて完成し、使用時に容器から自動的に注入されることで、同類間の相互依存関係を大幅に低減する.