如何从 Guice 的注入器检索带注释的实例?

假设我有一个模块:

Module extends AbstractModule
{
@Override
protected void configure()
{
bind(String.class).
annotatedWith(Names.named("annotation")).
toInstance("DELIRIOUS");
}
}

我想测试这个模块,检查它是否在一个带有 Names.named("annotation")注释的 String字段中注入了正确的值,这个字段没有类和字段,但是直接从注入器中获得了值:

@Test
public void test()
{
Injector injector = Guice.createInjector(new Module());


// THIS IS NOT GOING TO WORK!
String delirious = injector.getInstance(String.class);


assertThat(delirious, IsEqual.equalTo("DELIRIOUS");
}
56573 次浏览

I'm using the following method

public <T> T getInstance(Class<T> type, Class<? extends Annotation> option) {
final Key<T> key = Key.get(type, option);
return injector.getInstance(key);
}

for this. In general, you still have the problem of creating the annotation instance, but here Names.named("annotation") works.

injector.getInstance(Key.get(String.class, Names.named("annotation")));