AutowiredAnnotationBeanPostProcessor是spring实现自动装配的基石,根据前文​​《 internalAutowiredAnnotationProcessor在哪冒出来的?》​​,我们已经知道了AutowiredAnnotationBeanPostProcessor是什么时候被加入BeanDefinition,那它又是在哪个步骤被实例化的呢?

把断点打在 refresh()方法的invokeBeanFactoryPostProcessors处

AutowiredAnnotationBeanPostProcessor什么时候被实例化的?_实例化

我们可以看看invokeBeanFactoryPostProcessor上的注释

/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/

用刚过四级的英语水平翻译一下:实例化并调用所有的已注册的BeanFactoryPostProcessor,如果给定了顺序,按顺序来~

AutowiredAnnotationBeanPostProcessor什么时候被实例化的?_spring_02

那这里会不会实例化AutowiredAnnotationBeanPostProcessor呢?

可以看到,程序运行到时,beaDefinitionNames里面是包含了org.springframework.context.annotation.internalAutowiredAnnotationProcessor的

AutowiredAnnotationBeanPostProcessor什么时候被实例化的?_实例化_03

而存放完成实例化bean的singletonObects里面并没有,也就是说,到目前为止,AutowiredAnnotationBeanPostProcessor还未被实例化

AutowiredAnnotationBeanPostProcessor什么时候被实例化的?_实例化_04

下一步,执行invokeBeanFactoryPostProcessor,再看singletonObects,可以看到,只包含了ConfigurationClassPostProcessor、DefaultEventListenerFactory和EventListenerMethodProcessor的实例化对象

AutowiredAnnotationBeanPostProcessor什么时候被实例化的?_实例化_05

我们关心的AutowiredAnnotationBeanPostProcessor并没有实例化,我想这是因为属于BeanPostProcessor这个体系,而不属于BeanFactoryPostProcessor体系的原因

AutowiredAnnotationBeanPostProcessor什么时候被实例化的?_实例化_06

继续执行registerBeanPostProcessors(beanFactory),执行完可以看到,AutowiredAnnotationBeanPostProcessor已经完成了实例化。

AutowiredAnnotationBeanPostProcessor什么时候被实例化的?_spring_07

所以可以定位到,AutowiredAnnotationBeanPostProcessor的实例化发生在registerBeanPostProcessors(beanFactory)里面

跟进去看,方法上的注释都看似一样,实际完全不一样,对于invokeBeanFactoryPostProcessor是实例化并执行,而这里是:实例化并注册所有的BeanPostProcessor,也就是说,调用并不发生在这里。

/**
* Instantiate and register all BeanPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before any instantiation of application beans.
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

为什么呢?
我的理解是BeanFactoryPostProcessor增强的对象是BeanFactory,也就是容器,它们在容器创建过程的前后就需要被执行完,因为后面即将要创建用户定义的对象了,也就是执行finishBeanFactoryInitialization(beanFactory),再拖就来不及了,而BeanPostProcessor增强的对象是bean对象,应该围绕bean的创建前、创建中、创建后来执行,以达到增强bean的效果,故而这里只是实例化和注册,并没有执行。

实例化的过程也和普通bean对象一样,也是getBean/doGetBean/createBean/doCreate/createBeanInstance那一套,这个后面单独的内容来分析。

AutowiredAnnotationBeanPostProcessor什么时候被实例化的?_spring_08