• 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.
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5

    用刚过四级的英语水平翻译一下:实例化并调用所有的已注册的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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

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

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

    image.png

  • 相关阅读:
    Lyapunov optimization 李雅普诺夫优化
    两个请求,其中一个请求依赖另一个请求数据
    Python笔记六之多进程
    记录一个iOS使用陀螺仪3d效果的抖动问题
    Daniel Gross:硅谷的创投天才,能否成为下一个 Sam Altman?
    04.Ribbon负载均衡
    一个用于读取文件内容的 JavaScript 函数
    centos7基础操作
    6.9 条件变量的使用及注意事项
    Questions Per Chapter
  • 原文地址:https://blog.csdn.net/leisure_life/article/details/125462022