国产探花免费观看_亚洲丰满少妇自慰呻吟_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教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 达州市| 鱼台县| 曲周县| 华宁县| 辽宁省| 神农架林区| 内丘县| 汨罗市| 蓬安县| 蓝田县| 乌鲁木齐县| 新沂市| 永年县| 石屏县| 榆树市| 繁昌县| 穆棱市| 海安县| 永清县| 久治县| 乐至县| 郯城县| 城市| 颍上县| 九龙县| 子长县| 蕲春县| 黄龙县| 社旗县| 黔西县| 沈丘县| 吴旗县| 轮台县| 三亚市| 连平县| 浦县| 社会| 丰宁| 汉寿县| 大新县| 山丹县|