簡體   English   中英

Spring的BeanPostProcessor處理@Autowired注釋嗎?

[英]Is @Autowired annotation handled by BeanPostProcessor in Spring?

我聲稱:

  1. Spring從Java Config中讀取Bean定義
  2. BeanFactory從防御中創建豆
  3. 然后依賴項由BeanPostProcessors注入

但是碰巧這是不准確的:

@Configuration
@ImportResource("classpath:spring_config.xml")
public class JavaConfig {

    @Autowired
    MyBean bean;

    @Bean
    public Boolean isBeanAutowired(){
        return bean != null;
    }
}

isBeanAutowired bean已使用true初始化。

問題

在上下文中的所有bean初始化之前,自動Autowired邏輯如何工作?

是的@AutowiredBeanPostProcessor處理。 有關更多詳細信息,請參見org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor ,如果您嘗試找到更多相關信息,請參閱org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor

https://github.com/spring-projects/spring-framework/blob/master/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java

http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.html

最后,Spring能夠分析一個Bean(需要連接的其他Bean)的依賴關系,並確定初始化Bean的順序。 因此,可以在創建bean之后直接自動接線。 有一個例外,當Spring嘗試解決循環依賴關系時會發生這種情況。 然后,Spring將創建兩個bean並將它們彼此自動連接。 雖然這僅受限制。

它不是一個簡單的BeanPostProcessor 如果您嘗試通過以下方式直接實現它:

 public class MyAutowiredBeanPostProcessor implements BeanPostProcessor {

        @Autowired
        ApplicationContext context;

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            Class<?> beanClass = bean.getClass();
            Field[] declaredFields = beanClass.getDeclaredFields();
            for (Field field : declaredFields) {
                MyAutowired annotation = field.getAnnotation(MyAutowired.class);
                if (annotation != null){
                    Class<?> type = field.getType();
                    Object beanForInjection = context.getBean(type);
                    field.setAccessible(true);
                    ReflectionUtils.setField(field, bean, beanForInjection);
                }
            }
            return bean;
        }

您將看到它完美地“連接”了其他bean內的bean,但是卻沒有“連接” Java Configuration類中的任何東西。 此外,如果僅通過postProcessBeforeInitialization方法中的println beanName跟蹤Bean進入bpp的順序,您將看到:

Bean came to bpp: org.springframework.context.event.internalEventListenerProcessor
Bean came to bpp: org.springframework.context.event.internalEventListenerFactory
Bean came to bpp: javaConfig
Initialized isBeanAutowired, and myBean is: null
Bean came to bpp: isBeanAutowired
Bean came to bpp: myBean

分析一個Bean(需要連接的其他Bean)的依賴關系,並確定初始化Bean的順序。

因此, AutowiredAnnotationBeanPostProcessor聽起來像是對BPP初始原理的少許違反。 這不再是單一的責任。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM