使用Spring,您可以定義一個數組屬性,並讓Spring注入從給定類型派生的每個(@Component)類中的一個。如何獲得Guice的所有實現者/接口的子類?
在Guice中是否有這樣的等價物?或者添加此行爲的擴展點?
使用Spring,您可以定義一個數組屬性,並讓Spring注入從給定類型派生的每個(@Component)類中的一個。如何獲得Guice的所有實現者/接口的子類?
在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<YourInterface>
任何地方:
class SomeClass {
@Inject public SomeClass(Set<YourInterface> allImplementations) {
...
}
}
這應與你所需要的。
Guice Multibindings要求您明確addBinding()A
& B
到YourInterface
。如果你想要一個更「透明」(自動)的解決方案,比如AFAIK Spring提供的開箱即用的功能,那麼假設Guice已經知道A
& B
,因爲你已經在其他地方擁有了對A
& B
的綁定,即使不明確,但只是隱含的,例如通過@Inject
別的地方,那麼只有到那時,你或者可以使用類似這樣的自動發現(inspired by as done here,基於accessing Guice injector in a Module):再次
class YourModule extends AbstractModule {
@Override protected void configure() { }
@Provides
@Singleton
SomeClass getSomeClass(Injector injector) {
Set<YourInterface> 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);
}
}
注意,這種方法不需要任何類路徑掃描;它只是查看IS-A YourInterface
的所有Injector中已知的綁定。
我正在嘗試。但它不工作。 http://stackoverflow.com/questions/43705146/get-all-the-instance-subclass-of-trait-using-google-guice – Sky 2017-04-30 10:11:33
確實如此。感謝您指點我正確的方向。 – 2011-05-24 21:38:28
您會在單獨的jar(「guice extension」)中找到Multibindings:http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.google.inject.extensions%22%20AND% 20a%3A%22guit-multibindings%22 – Peti 2016-09-12 06:52:51