日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯網營銷解決方案
SpringBoot 啟動時實現自動執(zhí)行代碼的幾種方式

SpringBoot 啟動時實現自動執(zhí)行代碼的幾種方式

  • 前言
  • java自身的啟動時加載方式
  • Spring啟動時加載方式
  • 代碼測試
  • 總結

前言

當然也可以去實現Spring的ApplicationRunner與CommandLineRunner接口去實現啟動后運行的功能。在這里整理一下,在這些位置執(zhí)行的區(qū)別以及加載順序。

在泰山等地區(qū),都構建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供網站設計、網站建設 網站設計制作按需網站策劃,公司網站建設,企業(yè)網站建設,高端網站設計,營銷型網站,成都外貿網站建設公司,泰山網站建設費用合理。

java自身的啟動時加載方式

static代碼塊

static靜態(tài)代碼塊,在類加載的時候即自動執(zhí)行。

構造方法

在對象初始化時執(zhí)行。執(zhí)行順序在static靜態(tài)代碼塊之后。

Spring啟動時加載方式

@PostConstruct注解

PostConstruct注解使用在方法上,這個方法在對象依賴注入初始化之后執(zhí)行。

ApplicationRunner和CommandLineRunner

SpringBoot提供了兩個接口來實現Spring容器啟動完成后執(zhí)行的功能,兩個接口分別為CommandLineRunner和ApplicationRunner。

這兩個接口需要實現一個run方法,將代碼在run中實現即可。這兩個接口功能基本一致,其區(qū)別在于run方法的入參。ApplicationRunner的run方法入參為ApplicationArguments,為CommandLineRunner的run方法入參為String數組。

何為ApplicationArguments

官方文檔解釋為:

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

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

Order注解

當有多個類實現了CommandLineRunner和ApplicationRunner接口時,可以通過在類上添加@Order注解來設定運行順序。

代碼測試

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

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");
}
}

執(zhí)行結果

總結

Spring應用啟動過程中,肯定是要自動掃描有@Component注解的類,加載類并初始化對象進行自動注入。加載類時首先要執(zhí)行static靜態(tài)代碼塊中的代碼,之后再初始化對象時會執(zhí)行構造方法。

在對象注入完成后,調用帶有@PostConstruct注解的方法。當容器啟動成功后,再根據@Order注解的順序調用CommandLineRunner和ApplicationRunner接口類中的run方法。

因此,加載順序為static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner.


分享題目:SpringBoot 啟動時實現自動執(zhí)行代碼的幾種方式
分享路徑:http://m.5511xx.com/article/cccehho.html