gpt4 book ai didi

java - 具有列表值的 Guice MapBinder

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:08:59 24 4
gpt4 key购买 nike

我有一项服务需要注入(inject) 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);
}
}

我需要有关在 juice 中配置 typeEnrichers Binder 的帮助这是我正在尝试的,但卡住了

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??*/))

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

最佳答案

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

我建议您为每个 MapBinder 关系创建一个 Provider。实际上 Multibinder 本身就是一个 List Provider,具体来说,它的 RealMultibinder 实现不幸的是包私有(private)并且禁止使用。如果它不是包私有(private)的,也许我们可以这样使用它。很可能它无论如何都行不通......恕我直言,这会很好。

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

关于java - 具有列表值的 Guice MapBinder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com