java - 如何使用 Guice 检索给定接口(interface)的多重绑定(bind)实现集

标签 java guice

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

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

此应用程序模块的测试类负责确保绑定(bind)适当的实现。对于非多重绑定(bind),使用 Injector.getInstance(Class<T> type) 就很简单了。 :

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

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

有办法做到这一点吗?

最佳答案

找到答案,使用:

Injector.findBindingsByType(TypeLiteral<T> type)

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

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

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

..并返回 List<Binding<FooInterface>> ,我可以断言预期的类是其中一个绑定(bind)的目标。

关于java - 如何使用 Guice 检索给定接口(interface)的多重绑定(bind)实现集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34790975/

相关文章:

java - 二分查找给出错误类型 "Collections is not applicable for the arguments"

java - 即使获取 204 作为 HTTP 状态代码,实体也不会保存在数据库中

java - 通用对象列表的 Guice 绑定(bind)

java - 如何管理不同模块之间的共享依赖关系?

java - spring batch自定义退出描述

java - 来自某个类的对象是否可以输出具有唯一 JLabel 的相同格式的 JPanel?

java - Guice:使用复杂的创建模式连接一个 bean

Guice:避免惰性注入(inject)

java - 这里有人知道获取进程列表的好跨平台方法吗?

Java:将具有重复项的复杂对象中的两个列表合并为一个有序列表