當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot配置在应用启动后立即执行某些方法代码案例
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot配置在应用启动后立即执行某些方法代码案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
springboot給我們提供了兩種“開機啟動”方式:ApplicationRunner和CommandLineRunner。
這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執行某些方法。我們可以通過實現ApplicationRunner和CommandLineRunner,來實現,他們都是在SpringApplication 執行之后開始執行的。
CommandLineRunner接口可以用來接收字符串數組的命令行參數,ApplicationRunner 是使用ApplicationArguments 用來接收參數的。
CommandLineRunner :
@Component public class MyCommandLineRunner implements CommandLineRunner{@Overridepublic void run(String... var1) throws Exception{System.out.println("This will be execute when the project was started!");} }ApplicationRunner :
@Component public class MyApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments var1) throws Exception{System.out.println("MyApplicationRunner class will be execute when the project was started!");} }這兩種方式的實現都很簡單,直接實現了相應的接口就可以了。
記得在類上加@Component注解。
如果想要指定啟動方法執行的順序,可以通過實現org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解來實現。
以ApplicationRunner 為例來分別實現。
Ordered接口:
@Component public class MyApplicationRunner implements ApplicationRunner,Ordered{@Overridepublic int getOrder(){return 1;//通過設置這里的數字來知道指定順序}@Overridepublic void run(ApplicationArguments var1) throws Exception{System.out.println("MyApplicationRunner1!");} }Order注解實現方式:
@Component @Order(value = 1) public class MyApplicationRunner implements ApplicationRunner{@Overridepublic void run(ApplicationArguments var1) throws Exception{System.out.println("MyApplicationRunner1!");}} 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的SpringBoot配置在应用启动后立即执行某些方法代码案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis在实际项目中使用实例
- 下一篇: SpringMVC简介-传统的Model