Springboot給我們提供了兩種“開機啟動”某些方法的方式:ApplicationRunner和CommandLineRunner。
這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執行某些方法。我們可以通過實現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. */@Componentpublic 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. */@Componentpublic 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;/** * Created by pangkunkun on 2017/9/3. */@Componentpublic 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;/** * Created by pangkunkun on 2017/9/3. * 這里通過設定value的值來指定執行順序 */@Component@Order(value = 1)public class MyApplicationRunner implements ApplicationRunner{ @Override public void run(ApplicationArguments var1) throws Exception{ System.out.println("MyApplicationRunner1!"); }}
這里不列出其他對比方法了,自己執行下就好。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選