Spring quartz Job不能依赖注入,Spring整合quartz Job任务不能注入

278 篇文章 1 订阅
47 篇文章 0 订阅

Spring quartz Job不能依赖注入,Spring整合quartz Job任务不能注入

Spring4整合quartz2.2.3中Job任务使用@Autowired不能注入

 

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

©Copyright 蕃薯耀 2017年8月29日

http://fanshuyao.iteye.com/

 

一、问题描述:

使用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。

 

 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

©Copyright 蕃薯耀 2017年8月29日

http://fanshuyao.iteye.com/

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值