日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Boot 启动加载数据 CommandLineRunner

發布時間:2025/3/21 javascript 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Boot 启动加载数据 CommandLineRunner 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

實際應用中,我們會有在項目服務啟動的時候就去加載一些數據或做一些事情這樣的需求。?
為了解決這樣的問題,Spring Boot 為我們提供了一個方法,通過實現接口 CommandLineRunner 來實現。

很簡單,只需要一個類就可以,無需其他配置。?
創建實現接口 CommandLineRunner 的類

package org.springboot.sample.runner;import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component;/*** 服務啟動執行** @author 單紅宇(365384722)* @myblog http://blog.csdn.net/catoop/* @create 2016年1月9日*/ @Component public class MyStartupRunner1 implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println(">>>>>>>>>>>>>>>服務啟動執行,執行加載數據等操作<<<<<<<<<<<<<");}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Spring Boot應用程序在啟動后,會遍歷CommandLineRunner接口的實例并運行它們的run方法。也可以利用@Order注解(或者實現Order接口)來規定所有CommandLineRunner實例的運行順序。

如下我們使用@Order 注解來定義執行順序。

package org.springboot.sample.runner;import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;/*** 服務啟動執行** @author 單紅宇(365384722)* @myblog http://blog.csdn.net/catoop/* @create 2016年1月9日*/ @Component @Order(value=2) public class MyStartupRunner1 implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println(">>>>>>>>>>>>>>>服務啟動執行,執行加載數據等操作 11111111 <<<<<<<<<<<<<");}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
package org.springboot.sample.runner;import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;/*** 服務啟動執行** @author 單紅宇(365384722)* @myblog http://blog.csdn.net/catoop/* @create 2016年1月9日*/ @Component @Order(value=1) public class MyStartupRunner2 implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println(">>>>>>>>>>>>>>>服務啟動執行,執行加載數據等操作 22222222 <<<<<<<<<<<<<");}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

啟動程序后,控制臺輸出結果為:

>>>>>>>>>>>>>>>服務啟動執行,執行加載數據等操作 22222222 <<<<<<<<<<<<< >>>>>>>>>>>>>>>服務啟動執行,執行加載數據等操作 11111111 <<<<<<<<<<<<<
  • 1
  • 2

根據控制臺結果可判斷,@Order 注解的執行優先級是按value值從小到大順序。

總結

以上是生活随笔為你收集整理的Spring Boot 启动加载数据 CommandLineRunner的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。