一、问题描述:
使用quartz实现动态任务时,在job定时任务中使用某个service时,通过加注解@Component、@Autowired注入时,定时任务执行时,获取的demoService 对象为null
实例代码如下:
public class DemoJob implements Job{
@Autowired
private DemoService demoService ;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//实现业务代码
List<String> list = demoService.query();
}
}
二、解决办法
1.自定义一个JobFactory,
/***
* 解决调用service 空指针
*/
@Service("jobFactory")
public class JobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
//调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
//进行注入
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
2.配置QuartzConfig ,把JobFactory 添加到factoryBean里面
@Configuration
public class QuartzConfig {
private static final Logger logger = LoggerFactory.getLogger(QuartzConfig .class);
@Autowired
public JobFactory jobFactory;
/**
* 方法名:
* 功能:定义quartz调度工厂
*/
@Bean
public SchedulerFactoryBean schedulerFactoryBean(){
SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
factoryBean.setJobFactory(jobFactory);
//是否覆盖之前的定时