springboot-CommandLineRunner-啟動時執行任務


一、CommandLineRunner的作用

項目啟動后,執行run方法中的代碼。

如下所示:

package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyStartupRunner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {
    System.out.println(">>>>>>>>>>>>>>>服務啟動執行,執行加載數據等操作<<<<<<<<<<<<<");
  }
}

 

二、如果有多個類實現CommandLineRunner接口,如何保證順序

使用@Order 注解,通過源碼查看,order的值越小優先級越高

如下所示:

package org.springboot.sample.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
@Order(value=2)
public class MyStartupRunner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服務啟動執行 2222 <<<<<<<<<<<<<");
    }
}    

 

三、CommandLineRunner接口在SpringBoot啟動時執行的順序

CommandLineRunner接口的run()方法會在spring bean初始化之后,SpringApplication run之前執行,可以控制在項目啟動前初始化資源文件,比如初始化線程池,提前加載好加密證書等
 

四、Springboot中的類似接口

ApplicationRunner

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM