How to get annotated instance from Guice injector?

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 adds the correct value to the String field, annotated with Names.named("annotation") without having a class and field, but getting 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"); } 
+65
java dependency-injection annotations guice configuration
Feb 25 2018-11-11T00:
source share
2 answers
 injector.getInstance(Key.get(String.class, Names.named("annotation"))); 
+136
Feb 25 2018-11-21T00:
source share

I am 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 instantiating an annotation, but Names.named("annotation") works here.

+11
Feb 25 2018-11-11T00:
source share



All Articles