1. 程式人生 > >SpringBoot系列: CommandLineRunner介面的用處

SpringBoot系列: CommandLineRunner介面的用處

========================================
使用 CommandLineRunner 對Spring Bean進行額外初始化
========================================

如果想要在Spring 容器初始化做一些額外的工作, 比如要對Spring Bean 物件做一些額外的工作, 首先想到的方式是, 直接將程式碼寫在 main() 函式的 SpringApplication.run()後, 比如:

@SpringBootApplication
public class PebbleDemoApplication {

    
public static void main(String[] args) throws IOException { SpringApplication.run(PebbleDemoApplication.class, args); //done something here } }

其實, 這樣的方式的方式不行的, 在main()方法中, 要想訪問到Spring 中的 bean 物件, 並不容易. Spring Boot 為我們提供了更好的方式, 即宣告我們自己的 CommandLineRunner Bean.

具體為: 新建類去實現 CommandLineRunner 介面, 同時為類加上 @Component 註解.
當Spring 容器初始化完成後, Spring 會遍歷所有實現 CommandLineRunner 介面的類, 並執行其run() 方法.
這個方式是最推薦的, 原因是:
1. 因為 Runner 類也是 @Component 類, 這樣就能利用上Spring的依賴注入, 獲取到 Spring 管理的bean物件.
2. 可以建立多個 Runner 類, 為了控制執行順序, 可以加上 @Order 註解, 序號越小越早執行.

下面程式碼列印文字的順序是:  step 1 -> step 3 -> step 4 -> step 5

@SpringBootApplication
public class PebbleDemoApplication {

    public static void main(String[] args) throws IOException {
        System.out.println("Step 1:  The service will  start");    //step 1
        SpringApplication.run(PebbleDemoApplication.class
, args); //step 2 System.out.println("Step 5: The service has started"); //step 5 } } @Component @Order(1) class Runner1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("Step 3: The Runner1 run ..."); } } @Component @Order(2) class Runner2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("Step 4: The Runner2 run ..."); } }

 

========================================
使用 CommandLineRunner 建立純粹的命令列程式
========================================
步驟:
1. pom.xml 中要將 spring-boot-starter-web 依賴去除, 換上 spring-boot-starter 基礎依賴包.
2. 按照上面的方式3, 新建 CommandLineRunner 類, 並宣告為 @Component.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency> 

 

=======================================
參考
=======================================
http://www.ityouknow.com/springboot/2018/05/03/spring-boot-commandLineRunner.html