使用Quartz来按期发送告警任务,告警Job如:html
public class AlarmJob implements Job { @Resource private StoreRepository storeRepository; @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { // 告警逻辑 } }
StoreRepository是Spring Boot中的bean,该Job被触发后,始终得不到该bean的实例,参考了https://blog.csdn.net/xiaobuding007/article/details/80455187java
配置一个JobFactoryspring
@Component public class JobFactory extends AdaptableJobFactory { /** * AutowireCapableBeanFactory接口是BeanFactory的子类 * 能够链接和填充那些生命周期不被Spring管理的已存在的bean实例 */ private AutowireCapableBeanFactory factory; public JobFactory(AutowireCapableBeanFactory factory) { this.factory = factory; } /** * 建立Job实例 */ @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { // 实例化对象 Object job = super.createJobInstance(bundle); // 进行注入(Spring管理该Bean) factory.autowireBean(job); //返回对象 return job; } }
并将该JobFactory配置到less
@Configuration @Slf4j public class SchedulerConfig { private JobFactory jobFactory; public SchedulerConfig(JobFactory jobFactory){ this.jobFactory = jobFactory; } @Bean(name="SchedulerFactory") public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setQuartzProperties(quartzProperties()); factory.setJobFactory(jobFactory); return factory; } @Bean public Properties quartzProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); //在quartz.properties中的属性被读取并注入后再初始化对象 propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } /* * quartz初始化监听器 */ @Bean public QuartzInitializerListener executorListener() { return new QuartzInitializerListener(); } /* * 经过SchedulerFactoryBean获取Scheduler的实例 */ @Bean(name="Scheduler") public Scheduler scheduler() throws IOException { return schedulerFactoryBean().getScheduler(); } }
配置完JobFactory以后,注入的问题获得解决。一开始我觉得是Quartz没作好,看了一下官方的tutorial,原来人家原本没打算自动支持Spring Boot的DI。ide
官方tutorial:spring-boot
http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-12.htmlthis