java - Inject values of a Map with Guice -


i have guice managed service injects couple of other services. other services used depending on key value passed service method. want make map maps service use corresponding key:

@inject private iservicea servicea;  @inject private iserviceb serviceb;  private map<string, iservice> mapping;  private map<string, iservice> getmapping() {     if (mapping == null) {         mapping = new hashmap<string, iservice>();         mapping.put("keya", servicea);         mapping.put("keyb", serviceb);     } }  @override public void myservicemethod(string key) {     iservice servicetouse = getmapping().get(key);     // ... use methods of identified service } 

this solution works seem awkward, because have have lazy initialization of mapping. tried use static block, instance members not yet initialized guice @ point.

i prefer inject mapping values directly guice, don't know how achieve this.

just use mapbinder, e.g.

protected void configure() {     mapbinder<string, iservice> mapbinder = mapbinder.newmapbinder(binder(), string.class, iservice.class);     mapbinder.addbinding("keya").to(iservicea.class);     mapbinder.addbinding("keyb").to(iserviceb.class); } 

then inject entire map, e.g.

public class iservicecontroller {    @inject    private map<string, iservice> mapping; } 

Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -