【问题标题】:How to retrieve the Set of Multibound implementations of a given interface with Guice如何使用 Guice 检索给定接口的 Multibound 实现集
【发布时间】:2016-01-14 21:51:41
【问题描述】:

我的应用程序是用 Guice 构建的。应用程序模块使用 Multibinder 绑定接口的多个实现。

Multibinder<FooInterface> newSetBinder = Multibinder.newSetBinder(binder(), FooInterface.class);
newSetBinder.addBinding().to(FooInterfaceImpl.class);
newSetBinder.addBinding().to(BarInterfaceImpl.class);

此应用程序模块的测试类负责确保绑定适当的实现。对于非 Multibound 绑定,使用 Injector.getInstance(Class&lt;T&gt; type) 很简单:

assertThat("Incorrect implementation bound", injector.getInstance(SomeInterface.class), instanceOf(SomeInterfaceImpl.class));

但是,这不适用于 Multibound 接口。我想返回给定接口的绑定集合,并断言集合包含预期的类。

有没有办法做到这一点?

【问题讨论】:

    标签: java guice


    【解决方案1】:

    找到答案,使用:

    Injector.findBindingsByType(TypeLiteral<T> type)
    

    这个方法Returns all explicit bindings for {@code type}.

    因此,我可以在我的测试类中使用以下内容:

    injector.findBindingsByType(new TypeLiteral<FooInterface>() {}))
    

    ..在返回的List&lt;Binding&lt;FooInterface&gt;&gt; 上,我可以断言预期的类是其中一个绑定的目标。

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-10
      • 1970-01-01
      相关资源
      最近更新 更多