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 對象, 並不容易.有兩個方法:

方法1: 入口類中, 新增一個函數, 打上注解 @PostConstruct , 則這個函數在入口類初始化完成后被調用. 

方法2: 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


免責聲明!

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



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