Spring 源码之核心加载方法(13) finishRefresh

13 AbstractApplicationContext#finishRefresh

定位: org.springframework.context.support.AbstractApplicationContext#finishRefresh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
// 清除资源缓存
clearResourceCaches();

// Initialize lifecycle processor for this context.
// 将刷新完毕时间传播到生命周期处理器
initLifecycleProcessor();

// Propagate refresh to lifecycle processor first.
// 首先将刷新完毕事件传播到生命周期处理器(触发 isAutoStartup 方法返回 true 的 SmartLifecycle#start 方法)
getLifecycleProcessor().onRefresh();

// Publish the final event.
// 发布事件
publishEvent(new ContextRefreshedEvent(this));

// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}

13.1 AbstractApplicationContext#initLifecycleProcessor

定位: org.springframework.context.support.AbstractApplicationContext#finishRefresh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断 beanFactory 是否已经存在生命周期处理器
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
// 如果已经存在,则将该bean赋值给lifecycleProcessor
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
// 如果不存在,则使用 DefaultLifecycleProcessor
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
// 将 DefaultLifecycleProcessor 作为默认的生命周期处理器,注册到 beanFactory 中
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}

13.2 DefaultLifecycleProcessor#onRefresh

定位: org.springframework.context.support.DefaultLifecycleProcessor#onRefresh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// org.springframework.context.support.DefaultLifecycleProcessor#onRefresh
public void onRefresh() {
startBeans(true);
this.running = true;
}

private void startBeans(boolean autoStartupOnly) {
// 检索所有适用的生命周期Bean:所有已经创建的单例Bean,以及所有 SmartLifeCycle Bean(即使它们被标记未延迟初始化)
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
// 各 phases 所对应的 LifecycleGroup Map
Map<Integer, LifecycleGroup> phases = new HashMap<>();
// 遍历所有 lifecycle bean,按阶段值分组
lifecycleBeans.forEach((beanName, bean) -> {
// SmartLifecycle : 生命周期接口的扩展,用于那些需要在 ApplicationContext 刷新 和/或 特定顺序关闭时 启动的对象。
// 如果不是 autoStartupOnly || (bean 是 SmartLifecycle 的实例) && bean指定在包含ApplicationContext的刷新时由容器自动启动
if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
// 获取 bean 的生命周期阶段(相位值)
int phase = getPhase(bean);
// 获取 phase 对应的 LifecycleGroup
LifecycleGroup group = phases.get(phase);
// 如果 group 不为 null
if (group == null) {
// 新建一个 LifecycleGroup 的实例
group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
//将 phase,group 绑定到 phases 中
phases.put(phase, group);
}
// 将beanName,bean绑定到 group 中
group.add(beanName, bean);
}
});
// 如果 phases 不是空集
if (!phases.isEmpty()) {
// 存放生命周期阶段(相位值)
List<Integer> keys = new ArrayList<>(phases.keySet());
// 按阶段值进行排序
Collections.sort(keys);
// 调用 lifecycleGroup 中的所有 lifecycle#start 方法
for (Integer key : keys) {
// 启动 key 对应的 LifecycleGroup
phases.get(key).start();
}
}
}

13.3 AbstractApplicationContext#publishEvent

定位: org.springframework.context.support.AbstractApplicationContext#publishEvent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");

// Decorate event as an ApplicationEvent if necessary
// 如果有必要,将事件装饰为 applicationEvent
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
}
else {
// 不是事件类型就转为事件类型
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}

// Multicast right now if possible - or lazily once the multicaster is initialized
// 如果可能,立即进行多播或者一旦初始化多播器就进入懒惰状态
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else {
// 获取事件广播器,发布事件
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}

// Publish event via parent context as well...
// 如果存在父容器,那么父容器也发布事件
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
this.parent.publishEvent(event);
}
}
}

13.3.1 SimpleApplicationEventMulticaster#multicastEvent

定位: org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
// 返回此广播器的当前任务执行程序
Executor executor = getTaskExecutor();
// getApplicationListeners方法是返回与给定事件类型匹配的应用监听器集合
// 遍历所有的监听器
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
if (executor != null) {
// 如果executor不为空,则使用executor调用监听器
executor.execute(() -> invokeListener(listener, event));
}
else {
// 否则直接调用监听器
invokeListener(listener, event);
}
}
}

protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
// 返回此广播器的当前错误处理程序
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
// 如果errorHandler不为null,则使用带错误处理的方式调用给定的监听器
doInvokeListener(listener, event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
// 否则直接调用给定的监听器
doInvokeListener(listener, event);
}
}

private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
// 触发监听器的onApplicationEvent方法,参数为给定的事件
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
// -> let's suppress the exception and just log a debug message.
Log logger = LogFactory.getLog(getClass());
if (logger.isTraceEnabled()) {
logger.trace("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}