public class N extends R {
private final A a;
private B b;
@Inject
N(@Assisted final A a, final B b) {
a= a;
b= b;
}
}
我对此的理解是我将提供的参数“a”,Guice依赖注入器将负责注入“b”正确吗?我是否需要为能够注入“b”的guice添加任何注释,如何注入“b”?
答案 0 :(得分:3)
Guice将根据您在B
中的配置方式注入Module
。除了@Inject
(您已经拥有)之外,您无需添加任何其他内容。以下是您班上更完整的示例:
public class GuiceExample {
static class N {
private final A a;
private B b;
@Inject
N(@Assisted final A a, final B b) {
this.a = a;
this.b = b;
}
}
static class A {}
static class B {}
static interface NFactory {
public N create(A a);
}
static class Module extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder().implement(A.class, A.class).build(NFactory.class));
bind(B.class); // Or however you want B to be bound...
}
}
@Test
public void test() {
Injector i = Guice.createInjector(new Module());
N n = i.getInstance(NFactory.class).create(new A());
}
}
您应该根据自己的B
方法绑定configure
。您可以将NFactory
注入需要从N
s生成A
的类中。