我想用GIN注入一个A类。 A类构造函数需要在运行时知道id以及另外两个B和C类.B和C构造函数需要与参数的A相同的id。
这是一个类的例子。
public class A {
@Inject
public A(String id, B b, C c)
{
...
}
}
public class B {
@Inject
public B(String id)
{
...
}
}
public class C {
@Inject
public C(String id)
{
...
}
}
如何在注射过程中将id传播到所有类?
一种解决方案是使用AssistedInjectionFactory和所有三个类的创建方法,但这需要修改A构造函数以便使用工厂来实例化B和C.
还有其他方法可以使用GIN并避免使用A构造函数样板代码吗?
答案 0 :(得分:3)
我会使用@Named
注释,并根据您想要计算ID值的方式,使用bindConstant
方法或Provider
:
...
@Inject public A(@Named("myId") String id, B b, C c)
...
@Inject public B(@Named("myId") String id)
...
@Inject public C(@Named("myId") String id)
public class MyModule extends AbstractGinModule {
protected void configure() {
// You can use bindConstant and compute the id in configure()
String myid = "foo_" + System.currentTimeMillis();
bindConstant().annotatedWith(Names.named("myId")).to(myId)
}
// Or you can use a provider to compute your Id someway
@Provides @Named("myId") public String getMyId() {
return "bar_" + System.currentTimeMillis();
}
}