【发布时间】:2017-01-13 17:15:26
【问题描述】:
Spring constructor injection of SLF4J logger - how to get injection target class?
我想在 Spring boot 中实现类似的功能。
我尝试了针对这个问题给出的解决方案,但似乎 BeanFactoryPostProcessor 的 postProcessBeanFactory 方法从未在我的 Spring-Boot 应用程序中被调用
下面是方法的实现:
@SuppressWarnings("unused")
public class LoggerBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String [] beanClasses = beanFactory.getBeanDefinitionNames();
for(String beanName : beanClasses){
Object beanObject = beanFactory.getBean(beanName);
if(beanObject.getClass().isAnnotationPresent(Loggable.class)){
try {
Field loggerField = beanObject.getClass().getDeclaredField("logger");
loggerField.setAccessible(true);
loggerField.set(beanObject, LoggerFactory.getLogger(beanObject.getClass()));
}catch (NoSuchFieldException | IllegalAccessException e){
e.printStackTrace();
}
}
}
}
【问题讨论】:
-
您是否将此类作为 bean 添加到配置中?
-
@KenBekov 我到底需要在 Spring Boot 项目中的什么地方添加它?
-
将此作为
public static@Bean方法添加到您的配置中。只添加类不会有任何作用。
标签: java spring spring-boot dependency-injection autowired