Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve annotated instance from Guice's injector?

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"); } 
like image 368
Boris Pavlović Avatar asked Feb 25 '11 13:02

Boris Pavlović


1 Answers

injector.getInstance(Key.get(String.class, Names.named("annotation"))); 
like image 75
ColinD Avatar answered Nov 01 '22 17:11

ColinD