如何从Guice的喷油器检索注释的实例? [英] How to retrieve annotated instance from Guice's injector?
本文介绍了如何从Guice的喷油器检索注释的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有一个模块:
模块扩展AbstractModule
{
@覆盖
保护无效配置()
{
绑定(为String.class)。
annotatedWith(Names.named(注解))。
toInstance(谵妄);
}
}
和我要测试的模块,并检查其注入与注释一个
无需类和字段,但直接从喷油器获取的值:字符串
字段正确的价值Names.named(注解 )
@Test
公共无效测试()
{
喷油器喷油= Guice.createInjector(新模块()); //这是行不通的!
字符串神志不清= injector.getInstance(为String.class); assertThat(神志不清,IsEqual.equalTo(谵妄);
}
解决方案
injector.getInstance(Key.get(为String.class,Names.named(注解)));
Let's say I have a module:
Module extends AbstractModule
{
@Override
protected void configure()
{
bind(String.class).
annotatedWith(Names.named("annotation")).
toInstance("DELIRIOUS");
}
}
and I want to test the module and check if it injects the right value in a String
field annotated with Names.named("annotation")
without having a class and a field but obtaining the value directly from the injector:
@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");
}
解决方案
injector.getInstance(Key.get(String.class, Names.named("annotation")));
这篇关于如何从Guice的喷油器检索注释的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文