Guice相当于Spring的@Autowire实例列表

spring的时候我这样做:

@Autowire List myInterfaces; 

那么这个列表将由实现MyInterface所有bean填充。 我没有创建List类型的bean。

我在Google Guice中寻找这种行为。

Sofar我去了:

 Multibinder myInterfaceBinder = MultiBinder.newSetBinder(binder(), MyInterface.class); 

现在,如果我有一个实现MyInterface的bean并将其绑定,请通过:

 bind(MyInterfaceImpl.class).asEagerSingleton(); 

它不会包含在我的multibinder中。 我需要补充一下:

 myInterfaceBinder.addBinding.to(MyInterfaceImpl.class); 

这比Spring提供的要复杂一些。 所以我很惊讶我是不是以错误的方式使用它。 那么有更简单的方法来实现这一目标吗?

我自己并没有这样使用它,但是根据Guice的API文档,我认为你应该能够写出比这更多的内容:

 bindListener(Matchers.subclassesOf(MyInterface.class), new TypeListener() { public  void hear(TypeLiteral typeLiteral, TypeEncounter typeEncounter) { myInterfaceBinder.addBinding().to(typeLiteral); } } 

然后,当您通过绑定实现时

 bind(MyInterfaceImpl.class).asEagerSingleton(); 

它应该自动添加到您的multibinder。

一个hacky解决方案是在循环中完成所有操作:

 Multibinder myInterfaceBinder = MultiBinder.newSetBinder(binder(), MyInterface.class); Class[] classes = { MyInterfaceImpl, YourInterfaceImpl.class, MyCatsInterfaceImpl }; for (Class c : classes) { bind(c).asEagerSingleton(); myInterfaceBinder.addBinding.to(c); } 

它很hacky,它仅适用于这种简单的情况,但它很简单且干燥。