When outputting Log in Java, use libraries such as Log4j and Logback, or use java.util.logging. Most libraries and APIs get and generate Logger instances as follows.
Logger logger = Logger.getLogger(Hoge.class);
Writing these in every class is a hassle. Let's find a simpler way to write using Spring.
It's almost an introduction to the implementation of this site. http://memorynotfound.com/spring-inject-logger-annotation-example/
Thank you.
If you are using Spring, you can inject Logger into the annotated filed as below.
@Log
private static Logger logger;
The amount of description is small, but it is not necessary to specify the argument class, so you can eliminate Logger's mistake (which should sometimes be copied and pasted).
I will explain how to implement it.
Create a Log annotation as shown below.
Log.java
@Retention(RUNTIME)
@Target(FIELD)
@Documented
public @interface Log {
}
Since it is referenced at runtime, it is @Retention (RUNTIME)
, and since the target is a field, it is @Target (FIELD)
.
LogInjector
Using Spring, write the code to inject Logger in the field with the @Log
annotation created earlier.
Create a BeanPostProcessor implementation of Spring as follows, and create a Logger in it.
@Component
public class LogInjector implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessBeforeInitialization(final Object bean, String name) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
// make the field accessible if defined private
ReflectionUtils.makeAccessible(field);
if (field.getAnnotation(Log.class) != null) {
Logger log = Logger.getLogger(bean.getClass());
field.set(bean, log);
}
}
});
return bean;
}
}
Now you are ready. After that, you can use it by following the steps below.
@Log
to the static filed of the class you want to inject Logger.Now you don't have to do getLogger
every time.
Recommended Posts