Spring源碼窺探之:擴展原理BeanFactoryPostProcessor

BeanPostPorcessor是在bean建立對象初始化先後進行攔截工做,而BeanFactoryPostProcessor是Bean工廠的後置處理器,在Bean定義加載完成以後,Bean實例初始化以前會調用postProcessBeanFactory方法.
1.實現類
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        int count = beanFactory.getBeanDefinitionCount();
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        for (String str : beanDefinitionNames) {
            System.out.println("----->" + str);
        }
        System.out.println("獲取容器中BeanDefinition的數量-------> " + count);
    }
}

2. 配置類,其中注入了一個實體類,跟一個MyBeanFactoryPostProcessor spring

/**
 * description
 *
 * @author 70KG
 * @date 2018/12/24
 */
@Configurationpublic class MyConfig {

    @Bean
    public People01 people01() {
        return new People01();
    }

    @Bean
    public MyBeanFactoryPostProcessor myBeanFactoryPostProcessor() {
        return new MyBeanFactoryPostProcessor();
    }

}

3. 測試類app

public class Test01 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class);
    }

}

4. 結果,可見postProcessBeanFactory方法先於構造方法執行ide

----->org.springframework.context.annotation.internalConfigurationAnnotationProcessor
----->org.springframework.context.annotation.internalAutowiredAnnotationProcessor
----->org.springframework.context.annotation.internalRequiredAnnotationProcessor
----->org.springframework.context.annotation.internalCommonAnnotationProcessor
----->org.springframework.context.event.internalEventListenerProcessor
----->org.springframework.context.event.internalEventListenerFactory
----->myConfig
----->people01
----->myBeanFactoryPostProcessor
獲取容器中BeanDefinition的數量-------> 9
People01無參構造執行...

 

BeanFactoryPostProcessor調用棧:
1. AnnotationConfigApplicationContext類中AnnotationConfigApplicationContext構造中的refresh().嘗試去刷新容器
2. AbstractApplicationContext類中refresh()方法的invokeBeanFactoryPostProcessors(beanFactory).
在初始化實例以前,首先對BeanFactory進行後置處理,目的就是爲了在全部的Bean定義都已經加載,但還未初始化以前,向容器中
增長屬性或者重寫Bean的定義信息(This allows for overriding or adding properties even to eager-initializing beans)
3. AbstractApplicationContext類中invokeBeanFactoryPostProcessors()方法中的PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())
4. PostProcessorRegistrationDelegate類中的invokeBeanFactoryPostProcessors()方法中的invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory)
5. PostProcessorRegistrationDelegate類中的invokeBeanFactoryPostProcessors()方法中的postProcessor.postProcessBeanFactory(beanFactory)進行回調.post

相關文章
相關標籤/搜索