2014-04-27 228 views
0

依賴注入(DI)背後的基本原理是對象只能通過構造函數參數,工廠方法的參數或者設置的屬性來定義它們的依賴關係(也就是說它們所處理的其他對象)對象實例在構造或從工廠方法返回後。注入依賴關係

這裏究竟是什麼工廠方法?

回答

1

看看last example in this Spring reference documentation section

這是該示例:

<bean id="exampleBean" class="examples.ExampleBean" factory-method="createInstance"> 
    <constructor-arg ref="anotherExampleBean"/> 
    <constructor-arg ref="yetAnotherBean"/> 
    <constructor-arg value="1"/> 
</bean> 

<bean id="anotherExampleBean" class="examples.AnotherBean"/> 
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/> 

叫exampleBean類:

public class ExampleBean { 

// a private constructor 
private ExampleBean(...) { 
    ... 
} 

// a static factory method; the arguments to this method can be 
// considered the dependencies of the bean that is returned, 
// regardless of how those arguments are actually used. 
public static ExampleBean createInstance (
    AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { 

    ExampleBean eb = new ExampleBean (...); 
    // some other operations... 
    return eb; 
} 

}

因此,使用相同的豆內部工廠方法創建bean的實例。依賴注入是通過將其他bean作爲參數傳遞給工廠方法來實現的。

0

工廠方法是對象創建的設計模式。 Factory Method定義了一個創建對象的接口,但是可以讓子類決定實例化哪些類。欲瞭解更多信息,你可以閱讀here