一、背景介绍
最近开发一个新项目,涉及许多定时任务。要求在每次项目重启时都要自动读取外部配置文件并自动地执行定时任务
二、两种实现方式
2.1 实现ApplicationRunner接口
package org.config;
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接口,执行顺序按照@Order注解的value值决定,值小先执行
* @version 0.0.1
*/
@Slf4j
@Component
@Order(value = 1)
public class MyApplicationRunner implements ApplicationRunner {
@Autowired
private TestService testService;
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("测试MyApplicationRunner");
// 同步缓存中的通知消息数目
testService.findAll();
}
}
2.2 实现CommandLineRunner接口
package org.config;
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接口,执行顺序按照@Order注解的value值决定,值小先执行
* @version 0.0.1
*/
@Slf4j
@Component
@Order(value = 2)
public class MyCommandLineRunner implements CommandLineRunner {
@Autowired
private TestService testService;
@Override
public void run(String... args) throws Exception {
log.info("执行MyCommandLineRunner");
testService.findAll();
}
}