CommandLineRunner和ApplicationRunner


使用場景

我們在開發過程中會有這樣的場景:需要在容器啟動的時候執行一些內容,比如:讀取配置文件信息,數據庫連接,刪除臨時文件,清除緩存信息,在Spring框架下是通過ApplicationListener監聽器來實現的。在Spring Boot中給我們提供了兩個接口來幫助我們實現這樣的需求。這兩個接口就是我們今天要講的CommandLineRunner和ApplicationRunner,他們的執行時機為容器啟動完成的時候。

不同點

共同點:其一執行時機都是在容器啟動完成的時候進行執行;其二這兩個接口中都有一個run()方法;

不同點:ApplicationRunner中run方法的參數為ApplicationArguments,而CommandLineRunner接口中run方法的參數為String數組。

官方說明:

  • Interface used to indicate that a bean should run when it is contained within   
  • a SpringApplication. Multiple CommandLineRunner beans can be defined   
  • within the same application context and can be ordered using the Ordered   
  • interface or @Order annotation.   
  • If you need access to ApplicationArguments instead of the raw String array consider using ApplicationRunner. 

使用Ordered接口或者Order注解修改執行順序

問題提出: 如果有多個實現類,而我們需要按照一定的順序執行的話,那么應該怎么辦呢?

解決方案:其一可以在實現類上加上@Order注解指定執行的順序;其二可以在實現類上實現Ordered接口來標識。

需要注意:數字越小,優先級越高,也就是@Order(1)注解的類會在@Order(2)注解的類之前執行。

 


免責聲明!

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



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