如何从 Guice 的注入器中检索带注释的实例? [英] How to retrieve annotated instance from Guice's injector?

查看:42
本文介绍了如何从 Guice 的注入器中检索带注释的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个模块:

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆