目錄:【持續更新。。。。。】
spring 部分常用注解
spring boot 學習之路1(簡單入門)
spring boot 學習之路2(注解介紹)
spring boot 學習之路3( 集成mybatis )
spring boot 學習之路4(日志輸出)
spring boot 學習之路5(打成war包部署tomcat)
spring boot 學習之路6(定時任務)
spring boot 學習之路6(集成durid連接池)
spring boot 學習之路7(靜態頁面自動生效問題)
spring boot 學習之路8 (整合websocket(1))
spring boot 學習之路9 (項目啟動后就執行特定方法)
概述:
spring boot 整理之路繼續前行,這次我說一下怎么在spring boot項目啟動后立即執行某一個特定的方法,已經要執行特定方法不止一個的時候的順序問題【順序問題我只說注解咋實現@Order】
分析:
這次我拿項目中某一個功能為案例,進行演示:
如何在項目啟動時啟動ftp服務器(java內嵌ftp服務器):如何在spring boot項目啟動時讓ftp服務器也隨之啟動呢?
方案:
針對上面的問題,我在spring boot中找到了解決方案。那就是spring boot給我們提供了兩個接口 ApplicationRunner和CommandLineRunner。這兩個接口是Springboot給我們提供了兩種“開機啟動”的方式
ApplicationRunner :
源碼如下:
public interface ApplicationRunner {
void run(ApplicationArguments var1) throws Exception;
}
CommandLineRunner :
源碼如下:
public interface CommandLineRunner {
void run(String... var1) throws Exception;
}
對比:
相同點:這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執行某些方法。我們可以通過實現ApplicationRunner和CommandLineRunner,來實現,他們都是在SpringApplication 執行之后開始執行的。
不同點:CommandLineRunner接口可以用來接收字符串數組的命令行參數,ApplicationRunner 是使用ApplicationArguments 用來接收參數的 【根據業務場景靈活運用】
代碼:
注意:在這我用了注解,如果選擇接口實現方式只需要實現Order接口即可,里面有個getOrder方法 返回個int值,值越小,越優先執行
/** * @Author:huhy * @DATE:Created on 2018/1/3 12:47 * @Modified By: * @Class 項目啟動后運行此方法:CommandLineRunner實現 */ @Component @Order(value=2) public class FtpInitRunner implements CommandLineRunner { @Override /** *@Author: huhy *@Package_name:com.huhy.web.common.runner *@Date:13:20 2018/1/3 *@Description:項目啟動后運行此方法 CommandLineRunner * //項目路徑 path = E:\IDE\workspace\ideaWorkspace\spring boot\spring-boot String path = System.getProperty("user.dir"); CommandLine.main(new String[]{path+"\\src\\main\\resources\\ftpserver\\ftpd-typical.xml"}); System.out.println("----------------------"+path); */ public void run(String... var1) throws Exception{ System.out.println("2222222222222222222222"); }
/** * @Author:huhy * @DATE:Created on 2018/1/3 13:20 * @Modified By: * @Class Description:ApplicationRunner 實現 */ @Component @Order(value = 1) //執行順序控制 public class FtpInitRunner2 implements ApplicationRunner{ @Override /** *@Author: huhy *@Package_name:com.huhy.web.common.runner *@Date:13:29 2018/1/3 *@Description: ApplicationRunner方式實現 */ public void run(ApplicationArguments applicationArguments) throws Exception { //項目路徑 path = E:\IDE\workspace\ideaWorkspace\spring boot\spring-boot String path = System.getProperty("user.dir"); CommandLine.main(new String[]{path+"\\src\\main\\resources\\ftpserver\\ftpd-typical.xml"}); System.out.println("----------------------"+path); System.out.println("111111111111111111111111"); }
啟動圖如下:
總結:
spring boot的項目啟動注意分為兩步:
實現相應接口(ApplicationRunner和CommandLineRunner) -----------》 加入注解 (@Component | @Order )