具有列表值的Guice MapBinder

时间:2018-03-05 09:29:19

标签: java dependency-injection guice multimap

我有一项需要注入mulitmap的服务 - Map<String, List<Enricher>>

public class EnrichService {
    private Map<String, List<Enricher>> typeEnrichers;

    @Inject
    public EnrichService(Map<String, List<Enricher>> typeEnrichers) {
        this.typeEnrichers = typeEnrichers;
    }

    public void enrich(Entity entity) {
        List<Enricher> enrichers = typeEnrichers.get(entity.type);
        //.. enriching entity with enrichers
    }
}

class Entity {
    String id;
    String type = "shapedColorful";
    String color;
    String shape;
}

interface Enricher {
    void enrich(Entity entity);
}

class ColorEnricher implements Enricher {
    @Inject
    private  ColorService colorService;
    public void enrich(Entity entity) {
        entity.color = colorService.getColor(entity.id);
    }
}

class ShapeEnricher implements Enricher {
    @Inject
    private ShapeService shapeService;
    public void enrich(Entity entity) {            
        entity.shape = shapeService.getShape(entity.id);
    }
}

我需要帮助配置果汁中的typeEnrichers粘合剂 这是我尝试的,但卡住了

bind(ColorService).to(ColorServiceImpl.class);
bind(ShapeService).to(ShapeServiceImpl.class);
MapBinder<RelationType, List<Enricher>> mapBinder = MapBinder.newMapBinder(
            binder(), 
            new TypeLiteral<String>() {},
            new TypeLiteral<List<Enricher>>() {});

mapBinder.addBinding("shapedColorful", to(/*how to bind list of Enrichers here??*/))

任何帮助,我如何绑定这样的多图?

1 个答案:

答案 0 :(得分:2)

您正在尝试将MapBinderMultibinder混合在一起。

我建议你为每个MapBinder关系创建一个Provider。实际上Multibinder本身就是一个列表Provider,具体来说,它的RealMultibinder实现是不可避免的包私有且禁止使用。如果它不是包私有,也许我们可以这样使用它。很可能它无论如何都不会起作用...... Imho,它会很好。

bind(ColorService).to(ColorServiceImpl.class);
bind(ShapeService).to(ShapeServiceImpl.class);
MapBinder<RelationType, List<Enricher>> mapBinder = MapBinder.newMapBinder(
            binder(), 
            new TypeLiteral<String>() {},
            new TypeLiteral<List<Enricher>>() {});

mapBinder.addBinding("shapedColorful", toProvider(Multibinder.newSetBinder(this.binder(), Enricher.class).addBinding().to(ColorService.class).addBinding().to(ShapeService.class).asEagerSingleton()))

您仍然可以创建提供商并使用它:

public class ShapeColorfulProvider implements Provider<List<Enricher>> {
 @Inject private ColorService colorService;
 @Inject private ShapeService shapeService;

 public List<Enricher> get() {
   return Lists.newArrayList(colorService,shapeService);
 }

}

然后

   mapBinder.addBinding("shapedColorful", toProvider(ShapeColorfulProvider.class))