国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

詳解Spring Boot 項目啟動時執行特定方法

2024-07-14 08:41:16
字體:
來源:轉載
供稿:網友

Springboot給我們提供了兩種“開機啟動”某些方法的方式:ApplicationRunner和CommandLineRunner。

這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執行某些方法。我們可以通過實現ApplicationRunner和CommandLineRunner,來實現,他們都是在SpringApplication 執行之后開始執行的。

CommandLineRunner接口可以用來接收字符串數組的命令行參數,ApplicationRunner 是使用ApplicationArguments 用來接收參數的,貌似后者更牛逼一些。

先看看CommandLineRunner :

package com.springboot.study;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;/** * Created by pangkunkun on 2017/9/3. */@Componentpublic class MyCommandLineRunner implements CommandLineRunner{  @Override  public void run(String... var1) throws Exception{    System.out.println("This will be execute when the project was started!");  }}

ApplicationRunner :

package com.springboot.study;import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.stereotype.Component;/** * Created by pangkunkun on 2017/9/3. */@Componentpublic class MyApplicationRunner implements ApplicationRunner {  @Override  public void run(ApplicationArguments var1) throws Exception{    System.out.println("MyApplicationRunner class will be execute when the project was started!");  }}

這兩種方式的實現都很簡單,直接實現了相應的接口就可以了。記得在類上加@Component注解。

如果想要指定啟動方法執行的順序,可以通過實現org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解來實現。

這里我們以ApplicationRunner 為例來分別實現。

Ordered接口:

package com.springboot.study;import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.core.Ordered;import org.springframework.stereotype.Component;/** * Created by pangkunkun on 2017/9/3. */@Componentpublic class MyApplicationRunner implements ApplicationRunner,Ordered{  @Override  public int getOrder(){    return 1;//通過設置這里的數字來知道指定順序  }  @Override  public void run(ApplicationArguments var1) throws Exception{    System.out.println("MyApplicationRunner1!");  }}

Order注解實現方式:

package com.springboot.study;import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.core.Ordered;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;/** * Created by pangkunkun on 2017/9/3. * 這里通過設定value的值來指定執行順序 */@Component@Order(value = 1)public class MyApplicationRunner implements ApplicationRunner{  @Override  public void run(ApplicationArguments var1) throws Exception{    System.out.println("MyApplicationRunner1!");  }}

這里不列出其他對比方法了,自己執行下就好。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 连江县| 青神县| 林口县| 双城市| 辽源市| 喜德县| 荣昌县| 宜春市| 荆门市| 上犹县| 曲沃县| 互助| 昭通市| 双城市| 竹北市| 安福县| 岑巩县| 靖江市| 龙州县| 威宁| 颍上县| 久治县| 泾源县| 双流县| 徐汇区| 东莞市| 瑞丽市| 太原市| 彭州市| 南漳县| 宁远县| 嫩江县| 科技| 新建县| 邹城市| 湘乡市| 临朐县| 宜丰县| 凭祥市| 邛崃市| 北流市|