首页>代码>Spring自定义日志注解拦截初始化Logger对象实现日志输出的实例>/spring-inject-logger-annotation-example/src/main/java/com/memorynotfound/LogInjector.java
package com.memorynotfound;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;

@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 = LoggerFactory.getLogger(bean.getClass());
                    field.set(bean, log);
                }
            }
        });
        return bean;
    }
}
最近下载更多
微信网友_6263159342649344  LV7 2022年12月16日
a82338181  LV7 2021年5月21日
白纸一长  LV3 2021年1月7日
iloary  LV2 2021年1月6日
最近浏览更多
LITIANYU084414  LV11 2022年12月31日
微信网友_6263159342649344  LV7 2022年12月16日
wang512237140  LV20 2022年11月24日
kwm2921944  LV10 2021年6月16日
fangen0005  LV25 2021年6月10日
15195859092  LV2 2021年5月21日
a82338181  LV7 2021年5月21日
sizeking  LV8 2021年4月12日
最代码-宋家辉  LV61 2021年3月20日
lris_luanling  LV11 2021年2月22日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友