一尘不染

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

java

假设我有一个模块:

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

阅读 183

收藏
2020-12-03

共1个答案

一尘不染

injector.getInstance(Key.get(String.class, Names.named("annotation")));
2020-12-03