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

46次阅读

共计 1391 个字符,预计需要花费 4 分钟才能阅读完成。

最近在遇到比拟一个问题,通常咱们在 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 办法中找到这段代码

踩坑记录一下。

正文完
 0