如何在Spring Boot中使用ApplicationRunner和CommandLineRunner

一、ApplicationRunner是什麼

在Spring Boot中,如果你需要在啟動應用程序時執行一些特定的代碼邏輯,可以使用Spring Boot提供的ApplicationRunner介面。實現該介面讓你的代碼在Spring Boot應用啟動後自動執行,因此可以用於執行一些初始化操作等。

二、CommandLineRunner是什麼

CommandLineRunner是另一個與ApplicationRunner類似的介面,同樣用於在Spring Boot應用啟動後執行一些特定的代碼邏輯。不同於ApplicationRunner,CommandLineRunner介面的run()方法接收一個字元串數組作為參數,該數組包含了啟動應用程序時傳遞給程序的所有命令行參數。

三、使用ApplicationRunner和CommandLineRunner

1. ApplicationRunner 示例代碼

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

我們創建了一個名為MyApplicationRunner的類,實現了ApplicationRunner介面,將我們希望執行的邏輯放在了run()方法中。在上面的示例中,我們只是簡單地輸出了一句話。

需要注意的是,ApplicationRunner介面的run()方法中接收的參數為ApplicationArguments類型,它包含了Spring Boot應用啟動時傳遞給程序的所有參數。ApplicationArguments中除了包含命令行參數外,還提供了許多方便我們獲取參數的方法。

2. CommandLineRunner 示例代碼

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
       
    @Bean
    public CommandLineRunner commandLineRunner(){
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                System.out.println("CommandLineRunner is running...");
            }
        };
    }
}

在上面的示例中,我們通過@Bean註解創建了一個CommandLineRunner類型的bean,並在其run()方法中輸出了一句話。因此,在Spring Boot應用啟動後,該bean中的run()方法會被自動執行。

需要注意的是,CommandLineRunner介面中的run()方法接收一個表示啟動應用程序時傳遞給程序的所有命令行參數的字元串數組。在上例中,我們未使用args參數,如果您需要訪問這些參數,只需在run()方法中使用該參數即可。

四、結語

使用ApplicationRunner和CommandLineRunner介面非常方便,幫助我們在Spring Boot應用程序啟動後執行特定的代碼邏輯。當您需要在項目啟動時完成一些特定的初始化操作時,請嘗試使用這兩個類並實現它們,它們的使用將使您的生活更輕鬆。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/271430.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-16 14:55
下一篇 2024-12-16 14:55

相關推薦

發表回復

登錄後才能評論