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

时间:2011-02-25 13:58:58

标签: java dependency-injection configuration annotations guice

假设我有一个模块:

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

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

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

2 个答案:

答案 0 :(得分:171)

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

答案 1 :(得分:12)

我正在使用以下方法

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")可以正常工作。