SpringBoot項目啟動后執行某個方法的方式(開機啟動)


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


免責聲明!

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



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