Search code examples
javadependency-injectionguice

Guice: Injecting map binding with @Named


I would like to have the following injection model. Is this possible with Guice?

Module:

protected void configure() {
    MapBinder<String, IService> mapBinder = MapBinder.newMapBinder(binder(), String.class, IService.class);
    mapBinder.addBinding("keyA").to(IServiceA.class);
    mapBinder.addBinding("keyB").to(IserviceB.class);
}

Class:

class SomeClass {
    private final IService service;

    @Inject
    SomeClass(@Named("KeyA") final IService serviceInstance) {
        this.service = serviceInstance;
    }
}

Solution

  • That is not what map binder are intended for. In your example a binding annotation would be the way to go: https://github.com/google/guice/wiki/BindingAnnotations

    protected void configure() {
        bind(IServiceA.class).annotatedWith(Names.named("keyA"));
        bind(IServiceB.class).annotatedWith(Names.named("keyB"));
    }