Search code examples
javaguice

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


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 this in Guice? Or an extension point to add this behavior?


Solution

  • 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<YourInterface> anywhere:

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

    That should match with what you need.