2014-11-24 89 views
0

我有一种情况,我需要在大约40个实例中将接口I绑定到类A,但只在其他两个实例中将其绑定到类B.我当然可以命名它,或者在所有42个案例中对它进行注释,但是如果我只能注释2个例外,它会更加干净。是否有可能特别针对所有没有注释的实例?Guice:绑定没有注释的参数

+0

作为兴趣点,在hk2中,您可以专门@注入一些不符合特定注释条件的东西。请参阅https://hk2.java.net/2.4.0-b06/apidocs/org/glassfish/hk2/api/Unqualified.html。我们不时发现这样的事情很有用 – jwells131313 2014-12-01 19:47:15

回答

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))); 
}