Spring quartz Job依赖注入使用详解
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 id="customJobFactory" class="cn.imovie.manage.task.job.CustomJobFactory"></bean>
3、将自定义CustomJobFactory注入到org.springframework.scheduling.quartz.SchedulerFactoryBean,具体如下:
<property name="jobFactory" ref="customJobFactory"></property>
完整代码如下:
<!-- 定时任务配置 start --> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 --> <property name="overwriteExistingJobs" value="true" /> <!--必须的,QuartzScheduler 延时启动,应用启动完后 QuartzScheduler 再启动 --> <property name="startupDelay" value="10" /> <!-- 设置自动启动 --> <property name="autoStartup" value="true" /> <property name="jobFactory" ref="customJobFactory"></property> <property name="applicationContextSchedulerContextKey" value="applicationContextKey" /> <property name="configLocation" value="classpath:spring-quartz.properties" /> </bean> <!-- 定时任务配置 end -->
4、然后就可以在Job任务类使用@Autowired注入service。
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关推荐
qingjiuquan 2020-05-15
Julywhj 2020-01-05
景泽元的编程 2019-12-03
与卿画眉共浮生 2017-07-27
横云断岭 2012-02-03
happyfling 2019-09-20
fairystepwgl 2016-03-22
longdan0 2018-04-20
missshy 2019-03-02
burning 2016-03-11
zhongjcbill 2015-04-21
Holyn 2014-11-21
MayMatrix 2013-11-03
chenhualeguan 2013-10-16
spprogrammer 2016-03-22