【问题标题】:Inject values of a Map with Guice使用 Guice 注入地图的值
【发布时间】:2015-06-19 08:23:14
【问题描述】:

我有一个Guice 托管服务,它注入了一些其他服务。其他服务的使用取决于传递给我的服务方法的键值。所以我想制作一个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 注入映射值,但我不知道如何实现。

【问题讨论】:

  • 我可能跑题了,您可以考虑使用不同的模式:您可以 @Provide 您的 IService 类,并使用 @Named 注释将它们中的每一个映射到一个字符串

标签: java dependency-injection guice


【解决方案1】:

只需使用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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多