2011-05-22 110 views

回答

11

這看起來像是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) { 
     ... 
    } 
} 

這應與你所需要的。

+0

確實如此。感謝您指點我正確的方向。 – 2011-05-24 21:38:28

+0

您會在單獨的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

6

Guice Multibindings要求您明確addBinding()A & BYourInterface。如果你想要一個更「透明」(自動)的解決方案,比如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中已知的綁定。

+0

我正在嘗試。但它不工作。 http://stackoverflow.com/questions/43705146/get-all-the-instance-subclass-of-trait-using-google-guice – Sky 2017-04-30 10:11:33

相關問題