Spring源码 13 IOC refresh方法8

Spring IOC 的核心是 AbstractApplicationContextrefresh 方法。
其中一共有 13 个主要方法,这里分析第 8 个:initApplicationEventMulticaster

1 AbstractApplicationContext

1-1 初始化应用消息广播器

initApplicationEventMulticaster()
protected void initApplicationEventMulticaster() {
    // 获取 Bean 工厂
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isTraceEnabled()) {
            logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    else {
        // 定义应用事件多播器
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        // 注册单例
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
                         "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
        }
    }
}

获取 Bean 工厂注册单例 在前面已经分析过,这里不再分析。

1-2 定义应用事件多播器

SimpleApplicationEventMulticaster(beanFactory)

2 SimpleApplicationEventMulticaster

public SimpleApplicationEventMulticaster(BeanFactory beanFactory) {
    // 设置 Bean 工厂
    setBeanFactory(beanFactory);
}

2-1 设置 Bean 工厂

public void setBeanFactory(BeanFactory beanFactory) {
   if (!(beanFactory instanceof ConfigurableBeanFactory)) {
      throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
   }
   this.beanFactory = (ConfigurableBeanFactory) beanFactory;
   if (this.beanClassLoader == null) {
      this.beanClassLoader = this.beanFactory.getBeanClassLoader();
   }
}

参考

https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click

https://www.bilibili.com/video/BV12Z4y197MU?spm_id_from=333.999.0.0

《Spring源码深度解析(第2版)》

版本

Spring 5.3.15

posted @ 2022-03-14 13:58  天航星  阅读(36)  评论(0编辑  收藏  举报