Search code examples
javaguice

Binding a Set<String> in Guice


I want to bind a Set in Guice like so:

public class TestModule extends AbstractModule {
    @Override
    protected void configure() {
        Set<String> testSet = Sets.newHashSet("Hello", "World");
        bind(Set.class).annotatedWith(Named.named("Test.Set")).toInstance(testSet);
    }
}

I have ensured that this module is being included when creating the injector. I try to use this bound Set later:

public class TestClass {
    @Inject
    public NewReleaseRunner(@Named("Test.Set") Set<String> testSet) {
        System.out.println(testSet.toString());
    }
}

However, this yields a failure: No implementation for java.util.Set<java.lang.String> annotated with @com.google.inject.name.Named(value=Test.Set) was bound.

My concern is that Set<String> is generic, but the binding is to a Set.class. What can I do to fix this issue?


Solution

  • I think you have two options. Replace

    bind(Set.class).annotatedWith(Named.named("Test.Set")).toInstance(testSet);
    

    with

    bind(new TypeLiteral<Set<String>>() {}).annotatedWith(Named.named("Test.Set")).toInstance(testSet);
    

    Or remove the module's configure() binding and instead add

    @Provides
    @Named("Test.Set")
    public Set<String> stringSet() {
        return Sets.newHashSet("Hello", "World");
    }