AutowiredAnnotationBeanPostProcessor什么时候被实例化的?

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

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

image.png

我们可以看看invokeBeanFactoryPostProcessor上的注释

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

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

image.png

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

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

image.png

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

image.png

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

image.png

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

image.png

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

image.png

所以可以定位到,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那一套,这个后面单独的内容来分析。

image.png

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值