如何从Guice的注射器中获取带注释的实例?


88

假设我有一个模块:

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

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

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

Answers:


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

15

我正在使用以下方法

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


4
我认为值得一提的是,原始解决方案专门针对命名规范。如果您已经创建了一个注释(特定于接口@Annotation),则只需以特定于getMethod的方式进行调用即可。
BoneSmuggler '16
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.