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
/** * 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. 测试类
public class Test01 { public static void main(String[] args) { AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class); } }
4. 结果,可见postProcessBeanFactory方法先于构造方法执行
----->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)进行回调.