springboot項目啟動自動觸發方法場景:
做這個的原因:前端數據一直在變化,導致我每次打包之后需要清緩存處理緩存數據,故而有了本文,在項目啟動之后自動執行指定方法,本文作用是實現同步緩存數據。
開始配置,有兩種方式:ApplicationRunner和CommandLineRunner
實現ApplicationRunner接口
import org.service.PushMessageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * 實現ApplicationRunner接口,執行順序按照value值決定,值小先執行 */ @Slf4j @Component @Order(value = 1) public class MyApplicationRunner implements ApplicationRunner { @Autowired private PushMessageService pushMessageService; @Override public void run(ApplicationArguments args) throws Exception { log.info("測試服務MyApplicationRunner"); pushMessageService.resetRedis(); } }
實現CommandLineRunner接口
import org.service.PushMessageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * 實現MyCommandLineRunner接口,執行順序按照value值決定,值小先執行 */ @Slf4j @Component @Order(value = 2) public class MyCommandLineRunner implements CommandLineRunner { @Autowired private PushMessageService pushMessageService; @Override public void run(String... args) throws Exception { log.info("執行MyCommandLineRunner"); // 同步緩存中的通知消息數目 pushMessageService.resetRedis(); } }
@Component注解相應的類,並重寫run方法,若存在多個啟動執行的任務,可利用在類上使用@Order注解來指定順序。
在上述兩個類中PushMessageService 為自己的service接口,具體是什么隨意,使用方式和controller使用一樣,這樣項目啟動之后日志打印順序為:
測試服務MyApplicationRunner 執行MyCommandLineRunner