Google guice has a built-in logger binding. But what if I want to use a commons-logging or log4j logger?
Can I get guice to inject a Log created by
LogFactory.getLog(CLASS.class)
But having the same behavior as in built-in binding:
The binding automatically sets the logger's name to the name of the class into which the Logger is being injected..
Does it even makes sense? Or shout I simply use the built-in java Logger? Or just use commons-logging without injections?
Guice figures out how to give you an Emailer based on the type. If it's a simple object, it'll instantiate it and pass it in. If it has dependencies, it will resolve those dependencies, pass them into it's constructor, then pass the resulting object into your object.
Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.
Overview of bindings in Guice. A binding is an object that corresponds to an entry in the Guice map. You add new entries into the Guice map by creating bindings.
The implementation is very easy to understand. We need to create Injector object using Guice class createInjector() method where we pass our injector class implementation object. Then we use injector to initialize our consumer class. If we run above class, it will produce following output.
The CustomInjections page on the Guice wiki describes exactly how to inject a logger named by the class it's being injected into.
It's your choice. I've successfully used logback
with Guice using the method detailed on the wiki.
Have a look at the sli4j project. It might be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With