場景
在啟動SpringBoot項目的啟動類之后需要其立即執行某方法。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
在項目下新建類,使這個類實現CommandLineRunner接口,此接口是springboot自帶的,接口定義如下
package org.springframework.boot; @FunctionalInterface public interface CommandLineRunner { void run(String... args) throws Exception; }
實現接口后需要重新run方法,在run方法中執行需要接着執行的邏輯
package com.ruoyi.web.imserver.config; import com.ruoyi.web.imserver.ServerLauncherImpl; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * <p> 啟動MobileIMSDK服務端 </p> * * @author : * @description : run方法在SpringBoot服務啟動之后會自動被調用 * @date : */ @Component @Order(value = 1) public class ChatServerRunner implements CommandLineRunner { @Override public void run(String... strings) throws Exception { System.out.println("公眾號:霸道的程序猿"); } }
啟動SpringBoot的啟動類,查看效果
這里的Order注解的value代表啟動的順序,value值越小,順訊越在前。