Every application needs logging. What's more: Every part of an application needs logging. This applies, in particular, to components created by the injector.
To perform logging, a component needs loggers. Obviously, one would like to have these injected. And this is, what the logger modules can do for you. Here's an example of a component with injected loggers:
package com.foo.myapp; import org.apache.log4j.Logger; public class MyComponent { @InjLogger private Logger log; public void run() { log.debug("run: ->"); // Do something here. ... log.debug("run: <-"); }
Three things should be noted at this point: * The example doesn't use the standard @Inject annotation, but a custom annotation @InjLogger, which is unsupported by any other JSR 330 implementation, apart from Commons Inject. (In most cases, one could extend the respective implementation to achieve the same purpose. For example, Guice explicitly supports custom annotations. * The injected logger will have the id "com.foo.myapp.MyComponent", same as the class name, into which the logger is being injected. If you would like another id, use @InjLogger(id="SomeOtherId") instead. * The above example uses Log4J as a logging system. As a consequence, the proper module to use in the example below will be the Log4jLoggerModule. For other modules, you would need a different logger injection module. Explicitly supported are Log4j 2 (Log4j2LoggerModule), SLF4J 2 (Slf4JLoggerModule), and Commons Logging (CommonsLoggingLoggerModule). (Adding support for others would be quite easy by deriving another subclass of AbstractLoggerInjectingModule.
And here's how to apply the module:
public class MyApp { public static void main() throws Exception { final IModule postConstructModule = new PostConstructModule(); final IModule loggerModule = new Log4jLoggerModule(); final IModule module1 = new MyModule1(); final IModule module2 = new MyModule2(); // Note: The PostConstructModule is first in the list. final IInjctor injector = CommonsInject.build(postConstructModule, loggerModule, module1, module2); // A binding for the controller was created automatically by the PostConstructModule. final ILifecycleController controller = injector.getInstance(ILifecycleController.class); // Initialize the beans with @PostConstruct controller.start(); // Do the real work here. ... // Terminate the beans with @PreDestroy controller.shutdown(); } }
For obvious reasons, the logger module must precede you own, custom modules, so that these can benefit from the bindings created by the logger module. The PostConstructModule in the example isn't mandatory. However, if you do use the PostConstructModule, it has to go first.