如何使用Guice获取接口的所有实现者/子类? [英] How to get all implementors/subclasses of an interface with Guice?

查看:634
本文介绍了如何使用Guice获取接口的所有实现者/子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring,您可以定义一个数组属性,并让Spring注入从给定类型派生的每个(@Component)类中的一个。

With Spring, you can define an array property and have Spring inject one of every (@Component) class that derives from the given type.

是否有等价物在Guice这个?或者添加此行为的扩展点?

Is there an equivalent for this in Guice? Or an extension point to add this behavior?

推荐答案

这看起来像Guice的用例 MultiBinder 。你可能有类似的东西:

This looks like a use case for Guice MultiBinder. You could have something like that:

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< YourInterface>

And you can inject a Set<YourInterface> anywhere:

class SomeClass {
    @Inject public SomeClass(Set<YourInterface> allImplementations) {
        ...
    }
}

这应符合您的需求。

这篇关于如何使用Guice获取接口的所有实现者/子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆