假设我有一个模块:
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");
}
发布于 2011-02-25 22:14:09
injector.getInstance(Key.get(String.class, Names.named("annotation")));
发布于 2011-02-25 22:13:47
我使用以下方法
public <T> T getInstance(Class<T> type, Class<? extends Annotation> option) {
final Key<T> key = Key.get(type, option);
return injector.getInstance(key);
}
为了这个。通常,您仍然会遇到创建注释实例的问题,但在这里Names.named("annotation")
可以工作。
https://stackoverflow.com/questions/5118082
复制相似问题