创建一个新的@Log
注释。
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {}
现在实行BeanPostProcessor
这使我们postProcessBeforeInitialization
方法,它使我们能够初始化之前管理的bean。我们搜索@Log
注释并注入LoggerFactory
的实现。
@Component
public class LoggerPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
Logger log = LoggerFactory.getLogger(bean.getClass());
ReflectionUtils.makeAccessible(field);
field.set(bean, log);
}
}, new ReflectionUtils.FieldFilter() {
@Override
public boolean matches(Field field) {
return field.isAnnotationPresent(Log.class);
}
});
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
,并使用@Log
标注在现场级来形容,我们要注入的记录器。
@Log
private Logger logger;
看看https://stackoverflow.com/questions/3923971/why-calling-loggerfactory-getlogger-every-time-is-not-recommended! –
不,但我创建了一个ILoggable接口,我创建了一个与链接中提到的方式相同的日志对象。创建了一个Log类并实现了ILoggable。当我在Log类中使用日志对象时,输出表明日志属于ILoggable而不是Log类。输出是类似这样的“cccservice.ILoggable:test”而不是“cccservice.Log:test” – Reza
你有2个选择:要么使用私有静态最终记录器LOG = LoggerFactory.getLogger(MethodHandles.lookup()。lookupClass ())'作为你的日志定义,你可以在IntelliJ Idea(Eclipse有类似的东西)中声明为活动模板,并且在输入模板词时,IDE将用propper代码替换这个词,或者使用项目Lombok并定义简单['@ Log','@ Slf4j',...](https://projectlombok.org/features/Log.html)关于课程级别的注释 –