SpringBoot內置生命週期事件詳解 SpringBoot源碼(十)

SpringBoot中文註釋項目Github地址:java

https://github.com/yuanmabiji...git

本篇接 SpringBoot事件監聽機制源碼分析(上) SpringBoot源碼(九)github

1 溫故而知新

溫故而知新,咱們來簡單回顧一下上篇的內容,上一篇咱們分析了SpringBoot啓動時廣播生命週期事件的原理,現將關鍵步驟再濃縮總結下:spring

  1. 爲廣播SpringBoot內置生命週期事件作前期準備:1)首先加載ApplicationListener監聽器實現類;2)其次加載SPI擴展類EventPublishingRunListener
  2. SpringBoot啓動時利用EventPublishingRunListener廣播生命週期事件,而後ApplicationListener監聽器實現類監聽相應的生命週期事件執行一些初始化邏輯的工做。

2 引言

上篇文章的側重點是分析了SpringBoot啓動時廣播生命週期事件的原理,此篇文章咱們再來詳細分析SpringBoot內置的7種生命週期事件的源碼。後端

3 SpringBoot生命週期事件源碼分析

分析SpringBoot的生命週期事件,咱們先來看一張類結構圖:

由上圖能夠看到事件類之間的關係:app

  1. 最頂級的父類是JDK的事件基類EventObject
  2. 而後Spring的事件基類ApplicationEvent繼承了JDK的事件基類EventObject
  3. 其次SpringBoot的生命週期事件基類SpringApplicationEvent繼承了Spring的事件基類ApplicationEvent
  4. 最後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的具體事件類繼承,源碼以下:spring-boot

// 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;
    /**
     * Create a new ApplicationEvent.
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public ApplicationEvent(Object source) {
        super(source);
        this.timestamp = System.currentTimeMillis();
    }
    /**
     * Return the system time in milliseconds when the event happened.
     */
    public final long getTimestamp() {
        return this.timestamp;
    }
}

能夠看到ApplicationEvent有且僅有一個屬性timestamp,該屬性是用來記錄事件發生的時間。源碼分析

3.3 SpringBoot的事件基類SpringApplicationEvent

SpringApplicationEvent類繼承了Spring的事件基類ApplicationEvent,是全部SpringBoot內置生命週期事件的父類,源碼以下:

/**
 * Base class for {@link ApplicationEvent} related to a {@link SpringApplication}.
 *
 * @author Phillip Webb
 */
@SuppressWarnings("serial")
public abstract class SpringApplicationEvent extends ApplicationEvent {
    private final String[] args;
    public SpringApplicationEvent(SpringApplication application, String[] args) {
        super(application);
        this.args = args;
    }
    public SpringApplication getSpringApplication() {
        return (SpringApplication) getSource();
    }
    public final String[] getArgs() {
        return this.args;
    }
}

能夠看到SpringApplicationEvent有且僅有一個屬性args,該屬性就是SpringBoot啓動時的命令行參數即標註@SpringBootApplication啓動類中main函數的參數。

3.4 SpringBoot具體的生命週期事件類

接下來咱們再來看一下SpringBoot內置生命週期事件即SpringApplicationEvent的具體子類們。

3.4.1 ApplicationStartingEvent

// ApplicationStartingEvent.java

public class ApplicationStartingEvent extends SpringApplicationEvent {
    public ApplicationStartingEvent(SpringApplication application, String[] args) {
        super(application, args);
    }
}

SpringBoot開始啓動時便會發布ApplicationStartingEvent事件,其發佈時機在環境變量Environment或容器ApplicationContext建立前但在註冊ApplicationListener具體監聽器以後,標誌標誌SpringApplication開始啓動。

3.4.2 ApplicationEnvironmentPreparedEvent

// ApplicationEnvironmentPreparedEvent.java

public class ApplicationEnvironmentPreparedEvent extends SpringApplicationEvent {
    private final ConfigurableEnvironment environment;
    /**
     * Create a new {@link ApplicationEnvironmentPreparedEvent} instance.
     * @param application the current application
     * @param args the arguments the application is running with
     * @param environment the environment that was just created
     */
    public ApplicationEnvironmentPreparedEvent(SpringApplication application,
            String[] args, ConfigurableEnvironment environment) {
        super(application, args);
        this.environment = environment;
    }
    /**
     * Return the environment.
     * @return the environment
     */
    public ConfigurableEnvironment getEnvironment() {
        return this.environment;
    }
}

能夠看到ApplicationEnvironmentPreparedEvent事件多了一個environment屬性,咱們不妨想一下,多了environment屬性的做用是啥?
答案就是ApplicationEnvironmentPreparedEvent事件的environment屬性做用是利用事件發佈訂閱機制,相應監聽器們能夠從ApplicationEnvironmentPreparedEvent事件中取出environment變量,而後咱們能夠爲environment屬性增長屬性值或讀出environment變量中的值。

舉個栗子: ConfigFileApplicationListener監聽器就是監聽了 ApplicationEnvironmentPreparedEvent事件,而後取出 ApplicationEnvironmentPreparedEvent事件的 environment屬性,而後再爲 environment屬性增長 application.properties配置文件中的環境變量值。

當SpringApplication已經開始啓動且環境變量Environment已經建立後,而且爲環境變量Environment配置了命令行和Servlet等類型的環境變量後,此時會發布ApplicationEnvironmentPreparedEvent事件。

監聽ApplicationEnvironmentPreparedEvent事件的第一個監聽器是ConfigFileApplicationListener,由於是ConfigFileApplicationListener監聽器還要爲環境變量Environment增長application.properties配置文件中的環境變量;此後還有一些也是監聽ApplicationEnvironmentPreparedEvent事件的其餘監聽器監聽到此事件時,此時能夠說環境變量Environment幾乎已經徹底準備好了。

思考: 監聽同一事件的監聽器們執行監聽邏輯時是有順序的,咱們能夠想一下這個排序邏輯是何時排序的?還有爲何要這樣排序呢?

3.4.3 ApplicationContextInitializedEvent

// ApplicationContextInitializedEvent.java

public class ApplicationContextInitializedEvent extends SpringApplicationEvent {
    private final ConfigurableApplicationContext context;
    /**
     * Create a new {@link ApplicationContextInitializedEvent} instance.
     * @param application the current application
     * @param args the arguments the application is running with
     * @param context the context that has been initialized
     */
    public ApplicationContextInitializedEvent(SpringApplication application,
            String[] args, ConfigurableApplicationContext context) {
        super(application, args);
        this.context = context;
    }
    /**
     * Return the application context.
     * @return the context
     */
    public ConfigurableApplicationContext getApplicationContext() {
        return this.context;
    }
}

能夠看到ApplicationContextInitializedEvent事件多了個ConfigurableApplicationContext類型的context屬性,context屬性的做用一樣是爲了相應監聽器能夠拿到這個context屬性執行一些邏輯,具體做用將在3.4.4詳述。

ApplicationContextInitializedEvent事件在ApplicationContext容器建立後,且爲ApplicationContext容器設置了environment變量和執行了ApplicationContextInitializers的初始化方法後但在bean定義加載前觸發,標誌ApplicationContext已經初始化完畢。

擴展: 能夠看到 ApplicationContextInitializedEvent是在爲 context容器配置 environment變量後觸發,此時 ApplicationContextInitializedEvent等事件只要有 context容器的話,那麼其餘須要 environment環境變量的監聽器只須要從 context中取出 environment變量便可,從而 ApplicationContextInitializedEvent等事件不必再配置 environment屬性。

3.4.4 ApplicationPreparedEvent

// ApplicationPreparedEvent.java

public class ApplicationPreparedEvent extends SpringApplicationEvent {
    private final ConfigurableApplicationContext context;
    /**
     * Create a new {@link ApplicationPreparedEvent} instance.
     * @param application the current application
     * @param args the arguments the application is running with
     * @param context the ApplicationContext about to be refreshed
     */
    public ApplicationPreparedEvent(SpringApplication application, String[] args,
            ConfigurableApplicationContext context) {
        super(application, args);
        this.context = context;
    }
    /**
     * Return the application context.
     * @return the context
     */
    public ConfigurableApplicationContext getApplicationContext() {
        return this.context;
    }
}

一樣能夠看到ApplicationPreparedEvent事件多了個ConfigurableApplicationContext類型的context屬性,多了context屬性的做用是能讓監聽該事件的監聽器們能拿到context屬性,監聽器拿到context屬性通常有以下做用:

  1. 從事件中取出context屬性,而後能夠增長一些後置處理器,好比ConfigFileApplicationListener監聽器監聽到ApplicationPreparedEvent事件後,而後取出context變量,經過context變量增長了PropertySourceOrderingPostProcessor這個後置處理器;
  2. 經過context屬性取出beanFactory容器,而後註冊一些bean,好比LoggingApplicationListener監聽器經過ApplicationPreparedEvent事件的context屬性取出beanFactory容器,而後註冊了springBootLoggingSystem這個單例bean
  3. 經過context屬性取出Environment環境變量,而後就能夠操做環境變量,好比PropertiesMigrationListener

ApplicationPreparedEvent事件在ApplicationContext容器已經徹底準備好時但在容器刷新前觸發,在這個階段bean定義已經加載完畢還有environment已經準備好能夠用了。

3.4.5 ApplicationStartedEvent

// ApplicationStartedEvent.java

public class ApplicationStartedEvent extends SpringApplicationEvent {
    private final ConfigurableApplicationContext context;
    /**
     * Create a new {@link ApplicationStartedEvent} instance.
     * @param application the current application
     * @param args the arguments the application is running with
     * @param context the context that was being created
     */
    public ApplicationStartedEvent(SpringApplication application, String[] args,
            ConfigurableApplicationContext context) {
        super(application, args);
        this.context = context;
    }
    /**
     * Return the application context.
     * @return the context
     */
    public ConfigurableApplicationContext getApplicationContext() {
        return this.context;
    }
}

ApplicationStartedEvent事件將在容器刷新後但ApplicationRunnerCommandLineRunnerrun方法執行前觸發,標誌Spring容器已經刷新,此時容器已經準備完畢了。

擴展: 這裏提到了 ApplicationRunnerCommandLineRunner接口有啥做用呢?咱們通常會在 Spring容器刷新完畢後,此時可能有一些系統參數等靜態數據須要加載,此時咱們就能夠實現了 ApplicationRunnerCommandLineRunner接口來實現靜態數據的加載。

3.4.6 ApplicationReadyEvent

// ApplicationReadyEvent.java

public class ApplicationReadyEvent extends SpringApplicationEvent {
    private final ConfigurableApplicationContext context;
    /**
     * Create a new {@link ApplicationReadyEvent} instance.
     * @param application the current application
     * @param args the arguments the application is running with
     * @param context the context that was being created
     */
    public ApplicationReadyEvent(SpringApplication application, String[] args,
            ConfigurableApplicationContext context) {
        super(application, args);
        this.context = context;
    }
    /**
     * Return the application context.
     * @return the context
     */
    public ConfigurableApplicationContext getApplicationContext() {
        return this.context;
    }
}

ApplicationReadyEvent事件在調用完ApplicationRunnerCommandLineRunnerrun方法後觸發,此時標誌SpringApplication已經正在運行。

3.4.7 ApplicationFailedEvent

// ApplicationFailedEvent.java

public class ApplicationFailedEvent extends SpringApplicationEvent {
    private final ConfigurableApplicationContext context;
    private final Throwable exception;
    /**
     * Create a new {@link ApplicationFailedEvent} instance.
     * @param application the current application
     * @param args the arguments the application was running with
     * @param context the context that was being created (maybe null)
     * @param exception the exception that caused the error
     */
    public ApplicationFailedEvent(SpringApplication application, String[] args,
            ConfigurableApplicationContext context, Throwable exception) {
        super(application, args);
        this.context = context;
        this.exception = exception;
    }
    /**
     * Return the application context.
     * @return the context
     */
    public ConfigurableApplicationContext getApplicationContext() {
        return this.context;
    }
    /**
     * Return the exception that caused the failure.
     * @return the exception
     */
    public Throwable getException() {
        return this.exception;
    }
}

能夠看到ApplicationFailedEvent事件除了多了一個context屬性外,還多了一個Throwable類型的exception屬性用來記錄SpringBoot啓動失敗時的異常。

ApplicationFailedEvent事件在SpringBoot啓動失敗時觸發,標誌SpringBoot啓動失敗。

4 小結

此篇文章相對簡單,對SpringBoot內置的7種生命週期事件進行了詳細分析。咱們仍是引用上篇文章的一張圖來回顧一下這些生命週期事件及其用途:

5 寫在最後

因爲有一些小夥伴們建議以前有些源碼分析文章太長,致使耐心不夠,看不下去,所以,以後的源碼分析文章若是太長的話,筆者將會考慮拆分爲幾篇文章,這樣就比較短小了,比較容易看完,嘿嘿。

【源碼筆記】Github地址:

https://github.com/yuanmabiji...

點贊搞起來,嘿嘿嘿!


公衆號【源碼筆記】專一於Java後端系列框架的源碼分析。

相關文章
相關標籤/搜索