Spring Extension (1) — BeanPostProcessor based Logger Injection

场景:

Log Wrapperslf4j,编码中每个类都需要通过

private static final Logger LOGGER = LoggerFactory.getLogger(ErrorHandler.class);

这种非智能的硬编码方式来生成logger实例.

优化:

在spring框架中,每个类实例化的是由spring ioc完成的.实现BeanPostProcessor接口 能够在实例初始化完成后做一些自定义的逻辑。

spring基于Annotation的初始化类就是实现了BeanPostProcessor接口。例如:@Required && RequiredAnnotationBeanPostProcessor

故使用如下方式自动化初始Logger实例-基于spring 2.5-3.x

1、定义Annotation

/**
* Log Annotation for Logger Injection
**/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface Log {
    String value() default "";
}

2、在目标类定义:

@Component
public class LoggerDemo{  
     @Log  
     private Logger logger;  
     //some methods  
     //some properties
}


3、自定义BeanPostProcessor


/**
 * init the slf4j logger in each spring bean
 */
@Component
public class LoggerBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
        ReflectionUtils.doWithFields(bean.getClass(),new FieldCallback() { // spring reflection utils
            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                ReflectionUtils.makeAccessible(field);

                if (field.getType().equals(Logger.class) && field.isAnnotationPresent(Log.class)) {//Log Annotation check
                    Log logAnnotation = field.getAnnotation(Log.class);
                    String loggerName = logAnnotation.value();
                    Logger logger = null;
                    if (loggerName != null && !loggerName.equals("")) {
                        logger = LoggerFactory.getLogger(loggerName);
                    }else {
                        logger = LoggerFactory.getLogger(bean.getClass());
                    }
                    field.set(bean, logger);// init value
                }
            }
        });
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值