I'm using Spring XML-based DI to create my classes.
Also I'm using log4j and I'm injecting org.apache.log4j.Logger
as a constructor argument in each class which needs it.
So I have a lot of entries in Spring config like following:
<bean id="myClass" class="com.myProject.MyClass">
...
<constructor-arg type="org.apache.log4j.Logger">
<bean class="org.apache.log4j.Logger" factory-method="getLogger">
<constructor-arg value="com.myProject.MyClass"/>
</bean>
</constructor-arg>
</bean>
Class code:
package com.myProject;
import org.apache.log4j.Logger;
public class MyClass {
private final Logger logger;
public MyClass (
...
Logger logger) {
...
this.logger = logger;
}
...
}
Although it works perfectly, I wonder if there is any possibility to default constructor-arg
of the logger to the class name, whose constructor the created logger should be passed to?
E.g. like this solution for Unity DI and log4net which are somewhat analogs in .Net.
Update:
I see two reasons of injecting Logger
rather than initializing it inside the class.
First of all, statements like private final Logger logger = LogManager.getLogger(MyClass.class);
are usually copy-pasted, so they are prone to mistake in the logger name.
Moverover, I'd like to cover error logging with unit tests, e.g. pass a mock of Logger
into the constructor and than verify that after some erroneous action logger.Error
has been called.