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
now ,fight for future

浙公网安备 33010602011771号