Spring Boot學習--項目啟動時執行指定service的指定方法


Springboot給我們提供了兩種“開機啟動”某些方法的方式:ApplicationRunnerCommandLineRunner

這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執行某些方法。我們可以通過實現ApplicationRunner和CommandLineRunner,來實現,他們都是在SpringApplication 執行之后開始執行的。

CommandLineRunner接口可以用來接收字符串數組的命令行參數,ApplicationRunner 是使用ApplicationArguments 用來接收參數的,貌似后者更牛逼一些。

先看看CommandLineRunner :

package com.springboot.study; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * Created by pangkunkun on 2017/9/3. */ @Component public class MyCommandLineRunner implements CommandLineRunner{ @Override public void run(String... var1) throws Exception{ System.out.println("This will be execute when the project was started!"); } }

ApplicationRunner :

package com.springboot.study; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; /** * Created by pangkunkun on 2017/9/3. */ @Component public class MyApplicationRunner implements ApplicationRunner { @Override public 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接口實現方式

package com.springboot.study; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; @Component public class MyApplicationRunner implements ApplicationRunner,Ordered{ @Override public int getOrder(){ return 1;//通過設置這里的數字來知道指定順序
 } @Override public void run(ApplicationArguments var1) throws Exception{ System.out.println("MyApplicationRunner1!"); } }

Order注解實現方式:

package com.springboot.study; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 這里通過設定value的值來指定執行順序 */ @Component @Order(value = 1) public class MyApplicationRunner implements ApplicationRunner{ @Override public void run(ApplicationArguments var1) throws Exception{ System.out.println("MyApplicationRunner1!"); } }

 


免責聲明!

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



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