我与一个特定的依赖注入问题所困扰,我只是似乎无法弄清楚。仅供参考:我对guice很陌生,但我有其他DI框架的经验 - 这就是为什么我认为这不应该很难实现。吉斯多个实现参数的构造函数与依赖
我在做什么: 我正在Lagom多模块项目,并使用吉斯作为DI。
我想实现的目标: 注入一些接口实现的多个命名实例(让我们称之为发布者,因为它将发布消息给kafka主题)传递给我的服务。 这个'发布者'注入了一些Lagom和Akka相关的服务(ServiceLocator,ActorSystem,Materializer等)。
现在,我想有这样的出版商的两个实例,并且每个将消息发布到不同的主题(每个主题一个如此出版商实例)。
我该怎么做到这一点? 我有一个或多个实例的同一主题没有问题,但如果我想为每个实例注入不同的主题名称我有一个问题。
所以,我的出版商实施的构造看起来像这样:
@Inject
public PublisherImpl(
@Named("topicName") String topic,
ServiceLocator serviceLocator,
ActorSystem actorSystem,
Materializer materializer,
ApplicationLifecycle applicationLifecycle) {
...
}
如果我想创建一个实例我会做这样的在我ServiceModule:
public class FeedListenerServiceModule extends AbstractModule implements ServiceGuiceSupport {
@Override
protected void configure() {
bindService(MyService.class, MyServiceImpl.class);
bindConstant().annotatedWith(Names.named("topicName")).to("topicOne");
bind(Publisher.class).annotatedWith(Names.named("publisherOne")).to(PublisherImpl.class);
}
}
我将如何绑定多个出版商每个人都有自己的话题?
我玩弄实现另一个私有模块:
public class PublisherModule extends PrivateModule {
private String publisherName;
private String topicName;
public PublisherModule(String publisherName, String topicName) {
this.publisherName = publisherName;
this.topicName = topicName;
}
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named("topicName")).to(topicName);
bind(Publisher.class).annotatedWith(Names.named(publisherName)).to(PublisherImpl.class);
}
}
但这使我无处因为你不能在你得到喷射器模块的配置方法:
Injector injector = Guice.createInjector(this); // This will throw IllegalStateException : Re-entry is not allowed
injector.createChildInjector(
new PublisherModule("publisherOne", "topicOne"),
new PublisherModule("publisherTwo", "topicTwo"));
唯一的解决方案是容易的,它的工作原理是,我改变我的PublisherImpl到抽象,加上他的抽象的“getTopic()”方法,并与主题覆盖增加两个实现。
但是这种解决方案是瘸子。为代码重用添加额外的继承并不是最佳实践。此外,我认为,吉斯肯定必须支持这样的功能。
的任何建议都欢迎。 KR,内伊奇