使用 Guice 注入 Map 的值

Inject values of a Map with Guice

我有一个 Guice managed service that injects a couple of other services. The other services are used depending on a key value that is passed to my service method. So I want to make a Map 将要使用的服务映射到相应的键:

@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
}

这个解决方案有效但看起来很笨拙,因为我必须对映射进行延迟初始化。我尝试使用 static 块,但此时 Guice 尚未初始化实例成员。

我更喜欢直接用 Guice 注入映射值,但我不知道如何实现。

只需使用 MapBinder,例如

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);
}

然后注入整个地图,例如

public class IServiceController {
   @Inject
   private Map<String, IService> mapping;
}