2012-09-01 101 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或公共无参数构造。
  • 但这有限制,为您的默认构造函数需要是相同的具体类的派生所以可能成为累赘。