Search code examples
javaguice

Injecting list of strings in Guice


I am trying to inject one arraylist of Strings in Guice. For that I am trying to construct list as following in module, which I can inject later into any class:

Multibinder<String> myList =
            Multibinder.newSetBinder(binder(), String.class);


myList.addBinding().to("Test1");
myList.addBinding().to("Test2");

In the above line I am getting following error:

The method to(Class<? extends String>) in the type LinkedBindingBuilder<String> is not applicable for the arguments (String)

In this context, I have found this: Guice : Inject an ArrayList of Strings, but I think given solution does not fit my use case.


Solution

  • Use .toInstance()

    myList.addBinding().toInstance("Test1");
    myList.addBinding().toInstance("Test2");`