2

我想在我的項目中使用picoContainer。 我對此知之甚少,但想要嘗試一下。使用和了解picoContainer

據我所知,我必須創建一個picoContainer和registercomponents與它。 我這樣做

public static PicoContainer getPicoContainer(){ 
    final MutablePicoContainer pico = new DefaultPicoContainer(); 
    pico.registerComponentImplementation(X.class); 
    pico.registerComponentImplementation(A.class); 
    pico.registerComponentImplementation(C.class); 
    pico.registerComponentImplementation(V.class); 
    pico.registerComponentImplementation(T.class); 
    pico.registerComponentImplementation(D.class); 

    return pico; 
} 

現在我的問題是,任何組件,以獲得其他組件,它需要在微微的句柄。 要訪問的任何組件需要做到這一點

A juicer = pico.getComponent(A.class); 

因此,在構造函數中的每個人,我需要在微微對象傳遞?我可以很容易地將其替換爲工廠。那有什麼意義?我確定我在這裏錯過了一些東西。 希望得到任何幫助。

+1

在其構造函數中需要另一個組件的組件應該已經獲得該組件的實例。 http://picocontainer.codehaus.org/constructor-injection.html - 類不應該負責創建所需的其他類,他們應該讓他們注入。 – zapl

回答

2

常見的模式是有一個主容器工廠的地方。 對於獨立應用程序,它可能是「public static void main()」入口點,對於web應用程序它將是前端控制器servlet或過濾器或上下文偵聽器(pico支持偵聽器的類)。 所以在入口點你用上面提到的方式配置容器「public static PicoContainer getPicoContainer()」,那麼你需要將控制權傳遞給容器中的入口點。最好的方法是讓至少一個容器的組件實現生命週期界面(http://picocontainer.codehaus.org/lifecycle.html),然後啓動容器並將所有東西連接起來。 在正常情況下,您不應該在條目配置旁邊訪問容器本身,以及諸如特殊工廠或交易分界等的東西。