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 = 7099057708183571937L;
/** System time when the event happened. */
private final long timestamp;

本文详细解析了SpringBoot启动过程中的7种内置生命周期事件,包括事件类结构、源码分析和应用场景,帮助理解事件的触发时机和用途。
最低0.47元/天 解锁文章
4048

被折叠的 条评论
为什么被折叠?



