Re: dependency injection and loggers
On 1/4/13 7:13 AM, markspace wrote:
On 1/4/2013 4:00 AM, Tomer wrote:
I love the concept of dependency injection via ctor. it simplifies
life and makes testing easy. what about logger? i usually instantiate
it in private static logger = Logger.getLogger(myclass); however this
is not dependency injection, should I pass the logger into each ctor?
this would look wierd... so what to do about loggers and depedency
injection?
I agree with you on both counts. Ctors are an excellent way of
implementing dependency injection, and static methods aren't.
However loggers are more of an aspect than a dependency. Absent some
other framework (AOP, for example, or some sort of annotation
processing), good old frameworks and libraries solve this problem. Have
a look at Apache logging:
<http://commons.apache.org/logging/>
Loggers can generally be configured externally to their instances.
Therefor you don't usually need to inject them.
On the other hand, there generally isn't any real requirement that
loggers be static. I have had occasion to create a class which uses a
different logger depending on the context in which that class was created.
public class MySomething {
private final Logger log;
public MySomething() {
this.log = Logger.getLogger(MySomething.class);
}
public MySomething(Logger log) {
this.log = log;
}
}