Spring在Bean实例化前的操作


        上一篇 Spring解析XML文件构建BeanDefinition对象介绍了BeanDefinition对象的构建与注册,但是还没有涉及到bean的实例化,这一篇先来看下bean实例化之前做了哪些事情。其中,国际化可以忽略,onRefresh方法是给子类去实现的。

在这里插入图片描述

一、invokeBeanFactoryPostProcessors

        这个方法中找到所有实现了BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor接口的类,提前实例化,排序后调用BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法和BeanFactoryPostProcessor的postProcessBeanFactory方法。

  1. BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法可以完成BeanDefinition的增删改查,如下图所示。
    在这里插入图片描述
  2. BeanFactoryPostProcessor接口是BeanDefinitionRegistryPostProcessor接口的父接口,它的postProcessBeanFactory方法参数是beanFactory,可以对beanFactory的属性进行修改,也能强转为BeanDefinitionRegistry,实现BeanDefinitionRegistry的一些功能。
    在这里插入图片描述

二、registerBeanPostProcessors

        registerBeanPostProcessors方法中首先找到所有实现了BeanPostProcessor接口的类,经历了提前实例化、排序等操作后,最终加入到了BeanFactory的beanPostProcessors容器。

上一篇介绍了,在component-scan标签解析过程中,最后注册了ConfigurationClassPostProcessor、AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor。其中,AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor实现了BeanPostProcessor接口。

在这里插入图片描述
在这里插入图片描述

三、initApplicationEventMulticaster和registerListeners

        initApplicationEventMulticaster方法构造了SimpleApplicationEventMulticaster监听器容器对象,并把它放入一级缓存中。
        监听器容器的使用在registerListeners,该方法获取所有实现了ApplicationListener接口的带有@Component注解的监听器,然后将监听器添加到applicationEventMulticaster。当然,也可以用applicationContext.addApplicationListener手动添加监听器。
        当有监听器对应的事件发布时,会触发监听器,这是典型的观察者设计模式。
        下图是Spring提供的5种标准事件,一般我们只关注ContextRefreshedEvent,这个事件是在finishRefresh中发布的。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/JustPlayCode/article/details/114395818
今日推荐