amith murakonda
amith murakonda

Reputation: 288

Binding Generic class object in Google guice

I have the following config file..

*.*.HM.Evaluation.Types = {
   "key1" = "value1";
   "key2" = "value2";
   "key3" = "value3";
};

I have the following constructor injection...

@Inject
public myConstuctor(@NonNull @Named("HM.Evaluation.Types") final Map<String , String> myMap) { ... }

This Works when I run my code using

Properties myProperties = new Properties().load(new FileReader("myConfig.properties"));
Names.BindProperties(Binder() , myProperties);

When I test my code using JUnits, I am not able to bind a

Map< String,String> class

The following code

Injector injector = Guice.CreateInjector((AbstractModule) -> {
bind(Map.class)
    .annotatedWith(Names.named("HM.Evaluation.Types")).toInstance(DUMMP_MAP);
});

gives me the following a google guice error

no implementation for java.lang.map< string , string> is found for the value Named(value = "HM.Evaluation.Types")

Is there a work around for this?

Upvotes: 0

Views: 1078

Answers (1)

Olivier Gr&#233;goire
Olivier Gr&#233;goire

Reputation: 35407

You can bind generics

Using a provider method (personal favorite)

class MyModule extends AbstractModule {
  ...
  @Provides
  @Singleton
  @Named("HM.Evaluation.Types")
  Map<String,String> provideDummpMap() {
    return DUMMP_MAP;
  }
}

Alternatively you can use TypeLiteral:

bind(new TypeLiteral<Map<String,String>>(){})
  .annotatedWith(Names.named("HM.Evaluation.Types"))
  .toInstance(DUMMP_MAP);

Upvotes: 1

Related Questions