如何使用Guice获取接口的所有实现者/子类?
使用Spring,您可以定义一个数组属性,并让Spring注入从给定类型派生的每个(@Component)类中的一个。
在Guice中有相同的效果吗? 或者是一个添加此行为的扩展点?
这看起来像Guice MultiBinder的用例。 你可能有类似的东西:
interface YourInterface { ... } class A implements YourInterface { ... } class B implements YourInterface { ... } class YourModule extends AbstractModule { @Override protected void configure() { Multibinder.newSetBinder(YourInterface.class).addBinding().to(A.class): Multibinder.newSetBinder(YourInterface.class).addBinding().to(B.class): } }
你可以在任何地方注入一个Set
:
class SomeClass { @Inject public SomeClass(Set allImplementations) { ... } }
这应该符合你的需要。
Guice Multibindings要求您明确地将A
& B
Binding()添加到YourInterface
。 如果你想要一个更加“透明”(自动)的解决方案,比如AFAIK Spring提供的开箱即用的解决方案,那么假设Guice已经了解A
& B
因为你已经在其他地方对A
& B
进行了绑定,即使不明确但只是隐含,例如通过其他地方的@Inject
,然后你才可以使用类似的东西进行自动发现( 灵感来自于这里所做的 ,基于访问模块中的Guice注入器 ):
class YourModule extends AbstractModule { @Override protected void configure() { } @Provides @Singleton SomeClass getSomeClass(Injector injector) { Set allYourInterfaces = new HashSet<>(); for (Key> key : injector.getAllBindings().keySet()) { if (YourInterface.class.isAssignableFrom(key.getTypeLiteral().getRawType())) { YourInterface yourInterface = (YourInterface) injector.getInstance(key); allYourInterfaces.add(yourInterface); } return new SomeClass(allYourInterfaces); } }
请再次注意,此方法不需要任何类路径扫描; 它只是查看Injector中所有IS-A YourInterface
已知绑定。