1. 程式人生 > 其它 >Spring Boot 啟動時自動執行程式碼的幾種方式,還有誰不會??

Spring Boot 啟動時自動執行程式碼的幾種方式,還有誰不會??

來源:blog.csdn.net/u011291072/article/details/81813662

前言

目前開發的SpringBoot專案在啟動的時候需要預載入一些資源。而如何實現啟動過程中執行程式碼,或啟動成功後執行,是有很多種方式可以選擇,我們可以在static程式碼塊中實現,也可以在構造方法裡實現,也可以使用@PostConstruct註解實現。

當然也可以去實現Spring的ApplicationRunnerCommandLineRunner介面去實現啟動後執行的功能。在這裡整理一下,在這些位置執行的區別以及載入順序。

java自身的啟動時載入方式

static程式碼塊

static靜態程式碼塊,在類載入的時候即自動執行。

構造方法

在物件初始化時執行。執行順序在static靜態程式碼塊之後。

Spring啟動時載入方式

@PostConstruct註解

PostConstruct註解使用在方法上,這個方法在物件依賴注入初始化之後執行。

ApplicationRunner和CommandLineRunner

SpringBoot提供了兩個介面來實現Spring容器啟動完成後執行的功能,兩個介面分別為CommandLineRunnerApplicationRunner

這兩個介面需要實現一個run方法,將程式碼在run中實現即可。這兩個介面功能基本一致,其區別在於run方法的入參。ApplicationRunner

的run方法入參為ApplicationArguments,為CommandLineRunner的run方法入參為String陣列。

何為ApplicationArguments

官方文件解釋為:

Provides access to the arguments that were used to run a SpringApplication.

在Spring應用執行時使用的訪問應用引數。即我們可以獲取到SpringApplication.run(…)的應用引數。

Order註解

當有多個類實現了CommandLineRunnerApplicationRunner介面時,可以通過在類上新增@Order註解來設定執行順序。

程式碼測試

為了測試啟動時執行的效果和順序,編寫幾個測試程式碼來執行看看。

Spring Boot 基礎就不介紹了,推薦下這個實戰教程:https://github.com/javastacks/spring-boot-best-practice

TestPostConstruct

@Component
public class TestPostConstruct {

    static {
        System.out.println("static");
    }
    public TestPostConstruct() {
        System.out.println("constructer");
    }

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct");
    }
}

TestApplicationRunner

@Component
@Order(1)
public class TestApplicationRunner implements ApplicationRunner{
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("order1:TestApplicationRunner");
    }
}

TestCommandLineRunner

@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println("order2:TestCommandLineRunner");
    }
}

執行結果

總結

Spring應用啟動過程中,肯定是要自動掃描有@Component註解的類,載入類並初始化物件進行自動注入。載入類時首先要執行static靜態程式碼塊中的程式碼,之後再初始化物件時會執行構造方法。

在物件注入完成後,呼叫帶有@PostConstruct註解的方法。當容器啟動成功後,再根據@Order註解的順序呼叫CommandLineRunnerApplicationRunner介面類中的run方法。

因此,載入順序為static>constructer>@PostConstruct>CommandLineRunnerApplicationRunner.

近期熱文推薦:

1.1,000+ 道 Java面試題及答案整理(2022最新版)

2.勁爆!Java 協程要來了。。。

3.Spring Boot 2.x 教程,太全了!

4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這才是優雅的方式!!

5.《Java開發手冊(嵩山版)》最新發布,速速下載!

覺得不錯,別忘了隨手點贊+轉發哦!