2012-09-01 102 views
2

有沒有辦法在Guice 3.0中聲明默認綁定?Guice - 默認綁定定義

這裏是我所期待的一個例子:

//Constructor for Class Impl1 
@Inject 
public Impl1 (@One IMyOwn own) 
{ 
    ... 
} 

//Constructor for Class Impl2 
@Inject 
public Impl2 (@Two IMyOwn own) 
{ 
    ... 
} 

//Declare a default binding 
bind(IMyOwn.class).to(DefaultMyOwn.class); 

//Then, if I want to bind a custom implementation for @Two 
bind(IMyOwn.class).annotatedWith(Two.class).to(TwoMyOwn.class); 

其實,這個例子不能工作,因爲我必須申報所有註釋的結合( @一二)。

Guice有解決方案嗎? 謝謝。

+0

我必須使用ToConstructorBindings嗎? [link](http://code.google.com/p/google-guice/wiki/ToConstructorBindings) – pass1

+0

關於'toConstructor'綁定:這適用於您無法用'@Inject'註釋構造函數的情況。既然你可以,這對你來說不是問題。 –

回答

0

Guice試圖儘可能多地檢查您的配置(又名。綁定)。這也意味着,Guice無法分辨@One的缺失綁定是否爲錯誤,或者應該映射到某個默認情況。

如果您對細節感興趣,請在Guice中查找BindingResolution序列。由於步驟4和步驟6處理綁定註釋,並且步驟6顯式禁止默認,所以我認爲您運氣不佳。

.6。如果依賴項具有綁定註釋,請放棄。 Guice不會爲註釋的依賴項創建默認綁定。

所以你能做的最好是提供吉斯有一種提示,@One應映射到這樣的預設:

bind(IMyOwn.class).annotatedWith(One.class).to(IMyOwn.class); 

所以你不需要說明具體的默認類DefaultMyOwn多倍。

+0

它會有點骯髒,順便說一句,如果它是唯一的方式..感謝這個答案。 – pass1

1

使用@Named綁定。

Guice Reference on Github:

吉斯帶有一個內置的綁定註釋@Named使用的字符串:

public class RealBillingService implements BillingService { 
    @Inject 
    public RealBillingService(@Named("Checkout") CreditCardProcessor processor) { 
    ... 
    } 

要綁定一個特定的名稱,使用Names.named()來創建一個實例傳遞給annotatedWith:

bind(CreditCardProcessor.class) 
    .annotatedWith(Names.named("Checkout")) 
    .to(CheckoutCreditCardProcessor.class); 

所以你的情況,

//Constructor for Class Impl1 
@Inject 
public Impl1 (@Named("One") IMyOwn own) 
{ 
    ... 
} 

//Constructor for Class Impl2 
@Inject 
public Impl2 (@Named("Two") IMyOwn own) 
{ 
    ... 
} 

和你的模塊將是這樣的:

public class MyOwnModule extends AbstractModule { 
    @Override 
    protected void configure() { 
    bind(IMyOwn.class) 
     .annotatedWith(Names.named("One")) 
     .to(DefaultMyOwn.class); 

    bind(IMyOwn.class) 
     .annotatedWith(Names.named("Two")) 
     .to(TwoMyOwn.class); 
    } 
} 
+0

在這種情況下,你不能僅僅綁定實現嗎?倉(Impl1.class)。爲了(DefaultMyOwn.class)? –

0

隨着吉斯4.X有Optional Binder

public class FrameworkModule extends AbstractModule { 
    protected void configure() { 
    OptionalBinder.newOptionalBinder(binder(), Renamer.class); 
    } 
} 

public class FrameworkModule extends AbstractModule { 
    protected void configure() { 
    OptionalBinder.newOptionalBinder(
       binder(), 
       Key.get(String.class, LookupUrl.class)) 
        .setDefault().toInstance(DEFAULT_LOOKUP_URL); 
    } 
} 

在Guice 3.0中,您可能能夠利用默認構造函數的自動綁定。

  • 使用單個@Inject或公共無參數構造。
  • 但這有限制,爲您的默認構造函數需要是相同的具體類的派生所以可能成爲累贅。