Spring源码 13 IOC refresh方法8

2022-10-20,,,,

本文章基于 Spring 5.3.15

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();
}
}

Spring源码 13 IOC refresh方法8的相关教程结束。

《Spring源码 13 IOC refresh方法8.doc》

下载本文的Word格式文档,以方便收藏与打印。