Injection Values Maps with Guice
I have a Guice managed service that injects several other services. Other services are used depending on the key value that is passed to my service method. So I want to do Map
that which renders the service to use with the appropriate 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 some methods of the identified service
}
This solution works, but it seems awkward because I have to have this lazy display initialization. I tried using a block static
, but the instance members are not yet initialized by Guice at this point.
I would rather enter the display values directly with Guice, but I don't know how.
+3
source to share
1 answer
Just use MapBinder
for example
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 you enter the whole card for example.
public class IServiceController {
@Inject
private Map<String, IService> mapping;
}
+6
source to share