2012-08-28 29 views
0

在Guice中,我有一個「Panel」類和一個「Controller」類。兩者都是相互關聯的。控制器有3個子類(比如A,B和C)。我想爲程序員提供一種簡單的方法,根據他們的需求,通過注入3個控制器之一來獲得面板實例。

例如,在一個特定的代碼點,程序員可能想要一個ControllerA注入的Panel的實例,但在另一個地方他可能需要PanelB和ControllerB。

我該如何做到這一點?在Guice中配置幾個注入

回答

1

你可以使用一個綁定註釋,讓用戶指定一個他們想要的東西: http://code.google.com/p/google-guice/wiki/BindingAnnotations

你會創建註釋是這樣的:

import com.google.inject.BindingAnnotation; 
import java.lang.annotation.Target; 
import java.lang.annotation.Retention; 
import static java.lang.annotation.RetentionPolicy.RUNTIME; 
import static java.lang.annotation.ElementType.PARAMETER; 
import static java.lang.annotation.ElementType.FIELD; 
import static java.lang.annotation.ElementType.METHOD; 

@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) 
public @interface WithClassA{} 
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) 
public @interface WithClassB{} 
... 

然後你的用戶的構造看起來像

@Inject 
public MyConstructor(@WithClassA Panel thePanel) {...} 

然後,當您執行綁定時,您將使用.annotatedWith:

bind(Panel.class) 
    .annotatedWith(WithClassA.class) 
    .toProvider(ProviderThatReturnsPanelConstructedWithA.class); 
bind(Panel.class) 
    .annotatedWith(WithClassB.class) 
    .toProvider(ProviderThatReturnsPanelConstructedWithB.class); 

以防萬一,這裏有一個關於如何建立供應商的文件:http://code.google.com/p/google-guice/wiki/ProviderBindings

+0

謝謝你的提示。然而,爲每個控制器創建一個註釋和一個提供者看起來有點矯枉過正,IMO。我的問題顯示了一個簡化的場景,但真正的項目涉及到使用數百個面板和控制器重構應用程序。 – magarciaschopohl

1

我想出了一個可能的解決方案:吉斯允許你綁定到提供者的實例,不僅一類。因此,你可以只創建一個供應商與一個參數的構造方法,並結合它像這樣:

綁定(Panel.class).annotatedWith(WithClassA.class).toProvider(新MYPROVIDER( 「A」))

構造函數的參數類型可以是任何其他類型,即枚舉或甚至註釋,傳入相同的WithClassA.class。

這是保存提供者的好方法。缺點是你的提供者沒有依賴注入,但在這種情況下,這是我可以不用的。