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();
}
}
}
}
最佳答案
Spring 应该知道您已经添加了一个新的 BeanFactoryPostProcessor,因此您应该将其声明为一个 bean 到您的配置中。 对于 xml 配置:
<bean class="your.package.LoggerBeanFactoryPostProcessor" />
对于 JavaConfig:
@Bean
public static BeanFactoryPostProcessor loggerBeanFactoryPostProcessor() {
return new LoggerBeanFactoryPostProcessor();
}
注意:一定要在您的 JavaConfig 中创建一个返回静态 BeanFactoryPostProcessor 的方法。没有它会很好地工作,直到你想使用其他一些与 spring 相关的功能。例如,使用属性 @Value
将不起作用。
来自documentation :
By marking this method as static, it can be invoked without causing instantiation of its declaring @Configuration class, thus avoiding the above-mentioned lifecycle conflicts. Note however that static @Bean methods will not be enhanced for scoping and AOP semantics as mentioned above. This works out in BFPP cases, as they are not typically referenced by other @Bean methods.
关于java - Spring 启动 : BeanFactoryPostProcessor's postProcessBeanFactory not getting called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41622559/