Spring quartz Job依赖注入使用详解
一、问题描述:
使用Spring整合quartz实现动态任务时,想在job定时任务中使用某个service时,直接通过加注解@Component、@Autowired是不能注入的,获取的对象为Null。如下面的代码:
@Component @PersistJobDataAfterExecution @DisallowConcurrentExecution public class TicketSalePriceLessThanLowestPriceJob implements Job{ @Autowired private XxxService xxxService; }
二、解决方案:
1、新增一个自定义类(CustomJobFactory),继承SpringBeanJobFactory,代码如下:
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; } }
2、在spring.xml文件配置CustomJobFactory,如下:
<bean></bean>
3、将自定义CustomJobFactory注入到org.springframework.scheduling.quartz.SchedulerFactoryBean,具体如下:
<property ref="customJobFactory"></property>
完整代码如下:
<!-- 定时任务配置 start --> <bean> <property ref="dataSource"></property> <!--可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 --> <property value="true" /> <!--必须的,QuartzScheduler 延时启动,应用启动完后 QuartzScheduler 再启动 --> <property value="10" /> <!-- 设置自动启动 --> <property value="true" /> <property ref="customJobFactory"></property> <property value="applicationContextKey" /> <property value="classpath:spring-quartz.properties" /> </bean> <!-- 定时任务配置 end -->
4、然后就可以在Job任务类使用@Autowired注入service。