How to retrieve annotated instance from Guice's injector?

JavaDependency InjectionConfigurationAnnotationsGuice

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoris PavlovićView Question on Stackoverflow
Solution 1 - JavaColinDView Answer on Stackoverflow
Solution 2 - JavamaaartinusView Answer on Stackoverflow