SpringBoot之CommandLineRunner接口和ApplicationRunner接口

我們在開發中可能會有這樣的情景。需要在容器啓動的時候執行一些內容。比如讀取配置文件,數據庫連接之類的。SpringBoot給我們提供了兩個接口來幫助我們實現這種需求。這兩個接口分別爲CommandLineRunner和ApplicationRunner。他們的執行時機爲容器啓動完成的時候。

這兩個接口中有一個run方法,我們只需要實現這個方法即可。這兩個接口的不同之處在於:ApplicationRunner中run方法的參數爲ApplicationArguments,而CommandLineRunner接口中run方法的參數爲String數組。下面我寫兩個簡單的例子,來看一下這兩個接口的實現。

CommandLineRunner

具體代碼如下:
[java] view plain copy
  1. package com.zkn.learnspringboot.runner;  
  2.   
  3. import org.springframework.boot.CommandLineRunner;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. /** 
  7.  * Created by zkn on 2016/8/12. 
  8.  */  
  9. @Component  
  10. public class TestImplCommandLineRunner implements CommandLineRunner {  
  11.   
  12.   
  13.     @Override  
  14.     public void run(String... args) throws Exception {  
  15.   
  16.         System.out.println("<<<<<<<<<<<<這個是測試CommandLineRunn接口>>>>>>>>>>>>>>");  
  17.     }  
  18. }  
執行結果爲:

ApplicationRunner接口

具體代碼如下:
[java] view plain copy
  1. package com.zkn.learnspringboot.runner;  
  2.   
  3. import org.springframework.boot.ApplicationArguments;  
  4. import org.springframework.boot.ApplicationRunner;  
  5. import org.springframework.stereotype.Component;  
  6.   
  7. /** 
  8.  * Created by zkn on 2016/8/12. 
  9.  * 注意:一定要有@Component這個註解。要不然SpringBoot掃描不到這個類,是不會執行。 
  10.  */  
  11. @Component  
  12. public class TestImplApplicationRunner implements ApplicationRunner {  
  13.   
  14.   
  15.     @Override  
  16.     public void run(ApplicationArguments args) throws Exception {  
  17.         System.out.println(args);  
  18.         System.out.println("這個是測試ApplicationRunner接口");  
  19.     }  
  20. }  
執行結果如下:

@Order註解

如果有多個實現類,而你需要他們按一定順序執行的話,可以在實現類上加上@Order註解。@Order(value=整數值)。SpringBoot會按照@Order中的value值從小到大依次執行。

Tips

如果你發現你的實現類沒有按照你的需求執行,請看一下實現類上是否添加了Spring管理的註解(@Component)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章