Search code examples
javaguice

Guice MapBinder: How to bind map<String, Hashset> in Guice using providesIntoSet?


Tried below implemetation:

private class TestModule extends AbstractModule {

    @Override
    public void configure() {
        MapBinder<String, Set<Filter>> filterBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<String>(){}, new TypeLiteral<Set<Filter>>(){});
        filterBinder.addBinding("firstKeyInMap").to(Key.get(new TypeLiteral<Set<Filter>>(){}, Names.named("Filters")));
    }

    @ProvidesIntoSet
    @Named("Filters")
    public Filter getFilter1() {
        return mock(Filter1.class);
    }

    @ProvidesIntoSet
    @Named("Filters")
    public Filter Filter2() {
        return mock(Filter2.class);
    }

}

Sadly I have an error. Any clue to correct it?

com.google.inject.CreationException: Unable to create injector, see the following errors:

No implementation for java.util.Set annotated with @com.google.inject.name.Named(value=Filters) was bound.


Solution

  • Error was Guice is not able to find an implementation for Set. Problem lies with @ProvidesIntoSet.

    Explored few web resources & found following statement from https://github.com/google/guice/wiki/Guice40

    Multibinder or MapBinder items can be bound using @ProvidesIntoSet or @ProvidesIntoMap by installing a MultibindingsScanner.

    I see that MultibindingsScanner module functionality will be implemented by default in java docs. I am not sure why I needed install this explicitly. BTW, I am using Guice 4.0.

    Installed MultibindingsScanner and everything worked like a charm.