gpt4 book ai didi

java - Spring 启动 : BeanFactoryPostProcessor's postProcessBeanFactory not getting called

转载 作者:行者123 更新时间:2023-11-30 07:57:03 26 4
gpt4 key购买 nike

Spring constructor injection of SLF4J logger - how to get injection target class?

我想在 Spring boot 中实现类似的功能。

我尝试了针对这个问题给出的解决方案,但似乎 BeanFactoryPostProcessorpostProcessBeanFactory 方法从未在我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com