我有一种情况需要在大约40个实例中将接口I绑定到类A,但仅在其他2个实例中将它绑定到类B.我当然可以命名它,或者在所有42个案例中对它进行注释,但如果我只能注释2个例外,它会更干净。是否可以特别针对没有注释的所有实例?
答案 0 :(得分:3)
您不必针对需要A实现的注入点 - 您只需要为它们编写绑定。回想一下,Guice中的每个绑定都用Key
表示,并确保为两个案例添加一个。这样,没有绑定注释的任何I
都会获得A
,并且正确注释的任何I
都会获得B
。
static interface I {}
static class A implements I {}
static class B implements I {}
static class C {
@Inject I a;
@Inject @Named("b") I b;
}
static class Module extends AbstractModule {
@Override
protected void configure() {
bind(I.class).to(A.class);
bind(I.class).annotatedWith(Names.named("b")).to(B.class);
}
}
@Test
public void test() {
Injector i = Guice.createInjector(new Module());
C c = i.getInstance(C.class);
assertThat(c.a, is(instanceOf(A.class)));
assertThat(c.b, is(instanceOf(B.class)));
}