Custom injection example in Google Guice
Google Guice supports custom injections using 2 endpoints: type listener and injection listener and registeration of end-points. You may read the whole theory behind here, where a Logging Injection using Log4J is explained.
Lets try to implement that and see what more is required. In order to test the whole exercise, we could embrace TestNG to write a sample unit test-case using a dummy class have a method. Lets write a simple class which uses the Log4J Logger instance, injected using InjectLogger.
public class LoggingUsage
{ @InjectLogger org.apache.log4j.Logger log;
public int doAddition(int a,int b)
{ int c = a+b;
log.info("Added result: "+c);
return c;
}
}
Lets us now a write a TestNG testcase to try and test the same.
public class CustomLoggerInjectionTest
{ LoggingUsage logUsage;
@BeforeMethod
public void initLogUsage()
{ logUsage = Guice.createInjector(new LoggerModule(),new MyLoggerModule()).getInstance(LoggingUsage.class);
}
@Test
public void testLogUsage()
{ int value = logUsage.doAddition(20, 15);
assertEquals(value,35);
}
static class MyLoggerModule extends AbstractModule
{ @Override
protected void configure()
{ bind(LoggingUsage.class);
}
}
}
[/sourcecode]
Lets examine this testcase. Just before test execution, we register the LoggerModule, which binds the LOG4J specific listeners (type/injections) and custom module to bind our custom class which needs Logger injection we wrote above, and instantiate the class that uses this Logger instance. When the test executes, the usage-class would already have a injected Logger and would execute without issues.