quartz与spring整合时, 任务Job不是由spring管理创建的,想用@Autowired在任务类中注入其他依赖无法生效。可扩展生成任务的工厂,创建好任务后,利用AutowireCapableBeanFactory的autowireBean()方法注入依赖。示例代码如下。
package com.susq.common.task.quartz.config;
import lombok.extern.slf4j.Slf4j;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.boot.autoconfigure.quartz.SchedulerFactoryBeanCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Component;
/**
* 功能简介:quartz 任务配置类
* 功能详解:
*
* @author su_shaoqing
* @date 2019/12/16
*/
@Slf4j
@Configuration
public class QuartzConfiguration {
@Component
static class MySchedulerFactoryBeanCustomizer implements SchedulerFactoryBeanCustomizer {
@Autowired
private AutowiringSpringBeanJobFactory autowiringSpringBeanJobFactory;
@Override
public void customize(SchedulerFactoryBean schedulerFactoryBean) {
log.info("my custom SchedulerFactoryBean");
Resource resource = new ClassPathResource("quartz.properties");
if (resource.exists()) {
schedulerFactoryBean.setConfigLocation(resource);
}
schedulerFactoryBean.setJobFactory(autowiringSpringBeanJobFactory);
}
}
@Component
static class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
@NonNull
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
final Object job = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(job);
return job;
}
}
}