我的应用程序是用 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/