有没有办法在 Guice 3.0 中声明默认绑定(bind)?
这是我期望的示例:
//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);
实际上,这个示例无法工作,因为我必须为所有注释(@One、@Two)声明一个绑定(bind)。
是否有解决方案可以使用 Guice 做到这一点? 谢谢。
最佳答案
使用@Named绑定(bind)。
Guice 附带一个使用字符串的内置绑定(bind)注释 @Named:
public class RealBillingService implements BillingService {
@Inject
public RealBillingService(@Named("Checkout") CreditCardProcessor processor) {
...
}
要绑定(bind)特定名称,请使用 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);
}
}
关于java - Guice - 默认绑定(bind)定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12226013/