java - Guice - 默认绑定(bind)定义

标签 java binding guice

有没有办法在 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 Reference on Github:

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/

相关文章:

java - ArrayList 添加方法抛出 IndexOutOfBoundsException

java - javac 是否优化 "foo".length()?

c# - 有没有办法绑定(bind)到 Keyboard.FocusedElement?

.net - 什么是 String.Format 的 WPF XAML 数据绑定(bind)等效项?

java - 现场注入(inject) Gin

java - 如何模拟测试中的失败

java - Swing - 最后一个 JMenuItem 占据 JMenuBar 上的其余空间

java - C++ 遗留项目工作流程的编程语言决策

java - 我在资源中注入(inject)了服务接口(interface),但无法弄清楚如何配置资源方法调用

java - Guice 检测未使用的绑定(bind)