Spring源码讲解(六)BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor的扩展区别
由于Spring源码过于庞大,文章中不会列出细节,须要大家花时间下去研究哦
这两个扩展点的触发时机基本类似,都是在BeanDefinition加载之后,Bean实例化之前。之所以称为基本类似是因为并非完全相同,官方文档对其接口方法的定义有所不同:
BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry:
All regular bean definitions will have been loaded,but no beans will have been instantiated yet.
意思是所有常规bd已经加载完毕,然后可以再添加一些额外的bd。
BeanFactoryPostProcessor#postProcessBeanFactory:
All bean definitions will have been loaded, but no beans will have been instantiated yet.
所有的bd已经全部加载完毕,然后可以对这些bd做一些属性的修改或者添加工作。
所以官网的建议是BeanDefinitionRegistryPostProcessor用来添加额外的bd,而BeanFactoryPostProcessor用来修改bd。
这里也可以从源码中看出来,参考PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors方法,从这里可以看出来Spring执行这两个扩展类的先后顺序是这样的:1.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry方法
2.BeanDefinitionRegistryPostProcessor#postProcessBeanFactory方法
3.BeanFactoryPostProcessor#postProcessBeanFactory方法
Spring的设计理念是执行完第一步之后,所有的bd就已经全都创建出来了,这里包含两种的bd:
第一种常规的bd:
这个bd是通过ConfigurationClassPostProcessor扫描出来的,因为ConfigurationClassPostProcessor也是BeanDefinitionRegistryPostProcessor的实现类,且其是最先执行的。
第二种就是我们自定义实现BeanDefinitionRegistryPostProcessor接口后添加的bd:
所以官方文档的注释为什么叫作:All regular bean definitions will have been loaded,but no beans will have been instantiated yet.This allows for adding further bean definitions before the next post-processing phase kicks in.
还没有评论,来说两句吧...