关于spring:Configuration中的来声明BeanPostProcessor和BeanFactoryPostProcessor

最近在遇到比拟一个问题,通常咱们在spring中应用@Configuration来注解一个类时,能够同时用Autowire 和@Value 给该配置类主动注入属性值,如下:


@Configuration
public class ConfigA {
   @Autowired
   private Environment environment;
   @Value("${name}")
   private string name;
   @Bean
   public A a() {
       A a = new A();
       a.name = name;
       return a;
   }
}

咱们失常状况下都是能主动注入environment和name的,然而当在configration 中如果申明了一个BeanPostProcessor时,如下:

   @Bean
    public MyBeanPostProcessor myBeanPostProcessor(A a) {
        log.info("env=:{}", environment);
        MyBeanPostProcessor myBeanPostProcessor = new MyBeanPostProcessor();
        myBeanPostProcessor.setA(a);
        return myBeanPostProcessor;
    }

你会发现打进去的log env 为null,同时A的name 也为null,这个配置类的 @Autowired和@Value都没有失效。
翻阅spring 的官网,其中有一段小tip,如下

    
Make sure that the dependencies you inject that way are of the simplest kind only. @Configuration classes are processed quite early during the initialization of the context, and forcing a dependency to be injected this way may lead to unexpected early initialization. Whenever possible, resort to parameter-based injection, as in the preceding example.

Also, be particularly careful with BeanPostProcessor and BeanFactoryPostProcessor definitions through @Bean. Those should usually be declared as static @Bean methods, not triggering the instantiation of their containing configuration class. Otherwise, @Autowired and @Value may not work on the configuration class itself, since it is possible to create it as a bean instance earlier than AutowiredAnnotationBeanPostProcessor.

意思就是BeanPostProcessor 和BeanFactoryPostProcessor 会在configuration 自身这个bean初始化之前,能够在spring onrefresh 办法中找到这段代码

踩坑记录一下。

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据