Can I have a Guice abstract module with a constructor & local instance to provide a dynamic binding? Can a Guice module have a constructor?
I understand that using providers/factory builder are better way, but in my case, I would end up creating n-providers or factory builder with concrete logic (nearly a hundred) for doing the same.
public class MyDynamicModule extends AbstractModule{
private NeededInterface imp;
public MyDynamicModule(NeededInterface neededImplimentation){
this.imp = neededImplimentation;
}
@Override
protected void configure() {
bind(NeededInterface.class)
.annotatedWith(Names.named("keyname"))
.toInstance(neededImplimentation);
/*.
.
.
.
*1000s of other binding configuration which are not related to the discussion**/
}
}
I know the alternatives, but I need to know if having this piece of code is wrong? If it is, I need to do a major revamp to replace just this one line of code, which in-turn would be a huge overhead for my application.
I needed to find a way to dynamically add a bind-configuration to an existing module. From performance point of view, the above logic seemed simple and straight forward.
答案 0 :(得分:1)
这样做很好。您将无法将任何依赖项注入NeededImplementation
,但只要您不需要注入任何依赖项就可以了。我想你在启动时有某种条件逻辑,它选择基于某种东西的不同实现?命令行参数?属性文件?您已经拥有执行此决策过程的代码;您应该能够将代码放入Provider<NeededInterface>
而不会有太多困难,但您没有提供详细信息。你建议你的构造函数有数百个参数吗?
如果您只有一个实现类,那么您可以这样做:
bind(NeededInterface.class)
.annotatedWith(Names.named("keyname"))
.to(NeededImplimentation.class)
.in(Singleton.class);
如果类有一个无参数构造函数,你会得到相同的结果。你不想让Guice为你创造对象的原因是什么?