解决Spring整合Quartz Job时Bean不能依赖注入的问题

一、问题描述

项目环境:Spring项目整合org.quartz-scheduler

问题描述:实现Job类的类中,不能使用@Autowired自动注入Bean

二、解决教程

  • 新建CustomJobFactory类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public class CustomJobFactory extends SpringBeanJobFactory{

@Autowired
private AutowireCapableBeanFactory capableBeanFactory;

@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
//调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
//进行注入
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}

}
  • 配置spring-context.xml
1
2
3
4
5
6
7
8
<bean id="customJobFactory" class="com.***.CustomJobFactory"></bean>

<!-- 声明任务工厂 -->
<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jobFactory" ref="customJobFactory"></property>
<property name="configLocation" value="classpath:/properties/quartz.properties" />
</bean>
  • 使用方式
1
2
3
4
5
6
7
8
9
10
11
@DisallowConcurrentExecution  
public class testJob implements Job{

@Autowired
private XxxService xxxService;

public void execute(JobExecutionContext context) throws JobExecutionException {
// ***
}

}

以上配置即可解决spring bean在quartz-scheduler中不能自动注入的问题。

查看评论