springboot 學習之路 9 (項目啟動后就執行特定方法)


 

 


概述:

    spring boot 整理之路繼續前行,這次我說一下怎么在spring boot項目啟動后立即執行某一個特定的方法,已經要執行特定方法不止一個的時候的順序問題【順序問題我只說注解咋實現@Order】


分析:

    這次我拿項目中某一個功能為案例,進行演示:

      如何在項目啟動時啟動ftp服務器(java內嵌ftp服務器):如何在spring boot項目啟動時讓ftp服務器也隨之啟動呢?


 

方案:

    針對上面的問題,我在spring boot中找到了解決方案。那就是spring boot給我們提供了兩個接口 ApplicationRunnerCommandLineRunner。這兩個接口是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  )


免責聲明!

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



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