Search code examples
javaguice

How to inject this map as a bean using guice?


I am trying to inject a map that is initialized using certain static constants in my class.

However, I am unable to proceed ahead since I am new to Guice and I am not really sure how can I use this map? The map that I want to inject is:

Map> MyMap in MyClass.

I wrote a class for MyInjectedMap containing the MyMap where it's going to be constructed as well. I wrote a module and bind this class there. But this doesn't work.

public class MyInjectedMap {

    private Map<String, List<String>> MyMap = new HashMap<>();

    private List<String> data = Arrays.asList("abc");

}

I want to populate the MyMap with the data array list that I have made. I want to ask, which method needs to be written in this class such that it provides me with MyMap for injection?


Solution

  • You're going to want to convert the MyInjectedMap to a provider, and then bind it appropriately in your Module. Assuming you don't want this map for ALL maps, you're going to either create a custom annotation or used the @Named provided by guice:

    public class MyMapProvider implements Provider<Map<String,List<String>> {
        private Map<String,List<String>> myMap = new HashMap<>();
    
        public Map<String,List<String>> get() {
            return myMap;
        }
    }
    

    And setup the injector:

    bind(new TypeLiteral<Map<String,List<String>>>(){}).annotatedWith(Names.named("MyMap")).toProvider(MyMapProvider.class);
    

    And then inject it:

    @Inject @Named("MyMap") Map<String,List<String>> myMap;
    

    https://github.com/google/guice/wiki/ProviderBindings