1. 程式人生 > >CommandLineRunner,ApplicationRunner

CommandLineRunner,ApplicationRunner

helloworld

 

springboot專案啟動之後初始化自定義配置類

前言

今天在寫專案的時候,需要再springboot專案啟動之後,載入我自定義的配置類的一些方法,百度了之後特此記錄下。

正文

方法有兩種:

1、 建立自定義類實現 CommandLineRunner介面,重寫run()方法。springboot啟動之後會預設去掃描所有實現了CommandLineRunner的類,並執行其run()方法。

複製程式碼

@Component
@Order(2)   //通過order值的大小來決定啟動的順序
public class AskForLeave implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        askForLeave();
    }

    public void askForLeave(){
        System.out.println("專案啟動了,執行了方法");
    }
}

複製程式碼

執行結果:

 

 2、建立自定義類實現ApplicationRunner 介面,重寫run()方法。

複製程式碼

@Component
@Order(3)
public class Hello implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {

        hello();
    }

    public void hello(){
        System.out.println("專案又啟動了,這次使用的是:繼承 ApplicationRunner");
    }
}

複製程式碼

結果如下:

關於二者的區別:

其實並沒有什麼區別,如果想獲取更加詳細的引數的時候,可以選擇使用ApplicationRunner介面。其引數型別為:ApplicationArguments 。