Spring Boot 初始化運行特定方法


Spring Boot提供了兩種 “開機自啟動” 的方式,ApplicationRunnerCommandLineRunner

這兩種方式的目的是為了滿足,在容器啟動時like執行某些方法。我們可以通過實現ApplicationRunner或者CommandLineRunner來實現,他們都是在SpringAppliaction執行之后開始執行的。這個特性可以讓我們自定義一些在容器啟動時需要初始化的邏輯

 

ApplicationRunner接口

官方doc:

Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple ApplicationRunner beans can be defined within the same application context and can be ordered using the Ordered

當該接口包含在SpringApplication中時執行。多個ApplicationRunner通過Order直接進行排序:

/**
 * 初始化類
 */
@Order(1) // @Order注解可以改變執行順序,越小越先執行
@Component
public class MyApplicationRunner1 implements ApplicationRunner {

    /**
     * 會在服務啟動完成后立即執行
     */
    @Override
    public void run(ApplicationArguments arg0) throws Exception {
        System.out.println("MyApplicationRunner1----" + arg0);
    }

}
/**
 * 初始化類
 */
@Order(2) 
@Component
public class MyApplicationRunner2 implements ApplicationRunner {

    /**
     * 會在服務啟動完成后立即執行
     */
    @Override
    public void run(ApplicationArguments arg0) throws Exception {
        System.out.println("MyApplicationRunner2----" + arg0);
    }

}

容器啟動后的運行結果:

可以看到多個ApplicationRunner執行順序是按照Order中的值執行的,並且每個的入參都是同一個ApplicationArguments實例(具體原因后面分析)

 

CommandLineRunner接口

二者的官方doc基本一樣,區別在於接收的參數不一樣

/**
 * 初始化類
 */
@Order(1) // @Order注解可以改變執行順序,越小越先執行
@Component
public class MyCommandLineRunner1 implements CommandLineRunner {

    /**
     * 會在服務啟動完成后立即執行
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLineRunner1----" + args);
    }

}
/**
 * 初始化類
 */
@Order(2)
@Component
public class MyCommandLineRunner2 implements CommandLineRunner {

    /**
     * 會在服務啟動完成后立即執行
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLineRunner2----" + args);
    }

}

容器啟動后的運行結果:

可以看到多個CommandLineRunner的執行效果跟ApplicationRunner一模一樣

 

最后看下源碼:

SpringApplication啟動時,會執行其run方法中的afterRefresh方法:

在afterRefresh中可以看到這兩個接口被執行,並且每個ApplicationRunner或CommandLineRunner實例都是用的同一個入參:

 


免責聲明!

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



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