1. 程式人生 > >CommandLineRunner和ApplicationRunner介面

CommandLineRunner和ApplicationRunner介面

在開發中可能會有這樣的情景。需要在容器啟動的時候執行一些內容。比如讀取配置檔案,資料庫連線之類的。SpringBoot給我們提供了兩個介面來幫助我們實現這種需求。這兩個介面分別為CommandLineRunner和ApplicationRunner。他們的執行時機為容器啟動完成的時候。這兩個介面中有一個run方法,我們只需要實現這個方法即可。這兩個介面的不同之處在於:ApplicationRunner中run方法的引數為ApplicationArguments,而CommandLineRunner介面中run方法的引數為String陣列.

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(args);
        System.out.println("測試ApplicationRunner介面");
    }
}

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(args);
        System.out.println("測試CommandLineRunner介面");
    }
}