SpringBoot中文注释项目Github地址:
https://github.com/yuanmabiji/spring-boot-2.1.0.RELEASE
本篇接 SpringBoot事件监听机制源码分析(上) SpringBoot源码(九)
1 温故而知新
温故而知新,我们来简单回顾一下上篇的内容,上一篇我们分析了SpringBoot启动时广播生命周期事件的原理,现将关键步骤再浓缩总结下:
- 为广播SpringBoot内置生命周期事件做前期准备:1)首先加载
ApplicationListener
监听器实现类;2)其次加载SPI扩展类EventPublishingRunListener
。 - SpringBoot启动时利用
EventPublishingRunListener
广播生命周期事件,然后ApplicationListener
监听器实现类监听相应的生命周期事件执行一些初始化逻辑的工作。
2 引言
上篇文章的侧重点是分析了SpringBoot启动时广播生命周期事件的原理,此篇文章我们再来详细分析SpringBoot内置的7种生命周期事件的源码。
3 SpringBoot生命周期事件源码分析
分析SpringBoot的生命周期事件,我们先来看一张类结构图:
由上图可以看到事件类之间的关系:
- 最顶级的父类是JDK的事件基类
EventObject
; - 然后Spring的事件基类
ApplicationEvent
继承了JDK的事件基类EventObject
; - 其次SpringBoot的生命周期事件基类
SpringApplicationEvent
继承了Spring的事件基类ApplicationEvent
; - 最后SpringBoot具体的7个生命周期事件类再继承了SpringBoot的生命周期事件基类
SpringApplicationEvent
。
3.1 JDK的事件基类EventObject
EventObject
类是JDK的事件基类,可以说是所有Java事件类的基本,即所有的Java事件类都直接或间接继承于该类,源码如下:
// EventObject.java
public class EventObject implements java.io.Serializable {
private static final long serialVersionUID = 5516075349620653480L;
/**
* The object on which the Event initially occurred.
*/
protected transient Object source;
/**
* Constructs a prototypical Event.
*
* @param source The object on which the Event initially occurred.
* @exception IllegalArgumentException if source is null.
*/
public EventObject(Object source) {
if (source == null)
throw new IllegalArgumentException("null source");
this.source = source;
}
/**
* The object on which the Event initially occurred.
*
* @return The object on which the Event initially occurred.
*/
public Object getSource() {
return source;
}
/**
* Returns a String representation of this EventObject.
*
* @return A a String representation of this EventObject.
*/
public String toString() {
return getClass().getName() + "[source=" + source + "]";
}
}
可以看到EventObject
类只有一个属性source
,这个属性是用来记录最初事件是发生在哪个类,举个栗子,比如在SpringBoot启动过程中会发射ApplicationStartingEvent
事件,而这个事件最初是在SpringApplication
类中发射的,因此source
就是SpringApplication
对象。
3.2 Spring的事件基类ApplicationEvent
ApplicationEvent
继承了DK的事件基类EventObject
类,是Spring的事件基类,被所有Spring的具体事件类继承,源码如下:
// ApplicationEvent.java
/**
* Class to be extended by all application events. Abstract as it
* doesn't make sense for generic events to be published directly.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class ApplicationEvent extends EventObject {
/** use serialVersionUID from Spring 1.2 for interoperability. */
private static final long serialVersionUID