溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring Boot如何初始化運(yùn)行特定方法

發(fā)布時間:2021-08-18 14:00:00 來源:億速云 閱讀:170 作者:小新 欄目:編程語言

這篇文章主要介紹了Spring Boot如何初始化運(yùn)行特定方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

Spring Boot提供了兩種 “開機(jī)自啟動” 的方式,ApplicationRunner和CommandLineRunner

這兩種方式的目的是為了滿足,在容器啟動時like執(zhí)行某些方法。我們可以通過實現(xiàn)ApplicationRunner或者CommandLineRunner來實現(xiàn),他們都是在SpringAppliaction執(zhí)行之后開始執(zhí)行的。這個特性可以讓我們自定義一些在容器啟動時需要初始化的邏輯

ApplicationRunner接口:

官方doc:

Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple ApplicationRunner beans can be defined within the same application context and can be ordered using the Ordered

當(dāng)該接口包含在SpringApplication中時執(zhí)行。多個ApplicationRunner通過Order直接進(jìn)行排序:

/**
 * 初始化類
 */
@Order(1) // @Order注解可以改變執(zhí)行順序,越小越先執(zhí)行
@Component
public class MyApplicationRunner1 implements ApplicationRunner {
  /**
   * 會在服務(wù)啟動完成后立即執(zhí)行
   */
  @Override
  public void run(ApplicationArguments arg0) throws Exception {
    System.out.println("MyApplicationRunner1----" + arg0);
  }
}
/**
 * 初始化類
 */
@Order(2) 
@Component
public class MyApplicationRunner2 implements ApplicationRunner {
  /**
   * 會在服務(wù)啟動完成后立即執(zhí)行
   */
  @Override
  public void run(ApplicationArguments arg0) throws Exception {
    System.out.println("MyApplicationRunner2----" + arg0);
  }
}

容器啟動后的運(yùn)行結(jié)果:

Spring Boot如何初始化運(yùn)行特定方法

可以看到多個ApplicationRunner執(zhí)行順序是按照Order中的值執(zhí)行的,并且每個的入?yún)⒍际峭粋€ApplicationArguments實例(具體原因后面分析)

CommandLineRunner接口:

二者的官方doc基本一樣,區(qū)別在于接收的參數(shù)不一樣

/**
 * 初始化類
 */
@Order(1) // @Order注解可以改變執(zhí)行順序,越小越先執(zhí)行
@Component
public class MyCommandLineRunner1 implements CommandLineRunner {
  /**
   * 會在服務(wù)啟動完成后立即執(zhí)行
   */
  @Override
  public void run(String... args) throws Exception {
    System.out.println("MyCommandLineRunner1----" + args);
  }
}
/**
 * 初始化類
 */
@Order(2)
@Component
public class MyCommandLineRunner2 implements CommandLineRunner {
  /**
   * 會在服務(wù)啟動完成后立即執(zhí)行
   */
  @Override
  public void run(String... args) throws Exception {
    System.out.println("MyCommandLineRunner2----" + args);
  }
}

容器啟動后的運(yùn)行結(jié)果:

Spring Boot如何初始化運(yùn)行特定方法

可以看到多個CommandLineRunner的執(zhí)行效果跟ApplicationRunner一模一樣

最后看下源碼:

SpringApplication啟動時,會執(zhí)行其run方法中的afterRefresh方法:

Spring Boot如何初始化運(yùn)行特定方法

在afterRefresh中可以看到這兩個接口被執(zhí)行,并且每個ApplicationRunner或CommandLineRunner實例都是用的同一個入?yún)ⅲ?/p>

Spring Boot如何初始化運(yùn)行特定方法

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Spring Boot如何初始化運(yùn)行特定方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI