1 2 3 4 5 6 7 8 9 10 | package com.shengwangi.demo; @Component public class MyClass { @Loggable Logger logger; public void myMethod() { // do some thing logger.info( "use the logger as usual" ); } } |
1. Define the annotation
Define the loggable annotation.1 2 3 4 5 6 7 8 9 10 11 12 | package com.shengwangi.demo; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention (RUNTIME) @Target (FIELD) @Documented public @interface Loggable {} |
2. Define LoggableInjector Class
Let's see the code first.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package com.shengwangi.demo; import java.lang.reflect.Field; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.stereotype.Service; import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils.FieldCallback; @Service public class LoggableInjector implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessBeforeInitialization( final Object bean, String beanName) throws BeansException { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { // make the field accessible if defined private ReflectionUtils.makeAccessible(field); if (field.getAnnotation(Loggable. class ) != null ) { Logger log = LoggerFactory.getLogger(bean.getClass()); field.set(bean, log); } } }); return bean; } } |
3. Use annotation @Loggable to inject logger
Like we already did in the beginning of this article, using the annotation to inject logger to your beans.1 | @Loggable Logger logger |
0 comments:
Post a Comment