How to get all implementors/subclasses of an interface with Guice?

后端 未结 2 552
余生分开走
余生分开走 2020-12-10 11:34

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

Is there an equivalent for thi

2条回答
  •  不知归路
    2020-12-10 11:44

    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):
        }
    }
    

    And you can inject a Set anywhere:

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

    That should match with what you need.

提交回复
热议问题