How to retrieve annotated instance from Guice's injector?

和自甴很熟 提交于 2019-12-03 01:00:21

问题


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

回答1:


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



回答2:


I'm using the following method

public <T> T getInstance(Class<T> type, Class<? extends Annotation> option) {
    final Key<T> key = Key.get(type, option);
    return injector.getInstance(key);
}

for this. In general, you still have the problem of creating the annotation instance, but here Names.named("annotation") works.



来源:https://stackoverflow.com/questions/5118082/how-to-retrieve-annotated-instance-from-guices-injector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!