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。
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!