欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring quartz Job依賴(lài)注入使用詳解

 更新時(shí)間:2017年08月30日 09:05:03   投稿:lqh  
這篇文章主要介紹了Spring quartz Job依賴(lài)注入使用詳解的相關(guān)資料,Spring quartz Job不能依賴(lài)注入,Spring整合quartz Job任務(wù)不能注入Spring4整合quartz2.2.3中Job任務(wù)使用@Autowired不能注入,需要的朋友可以參考下

Spring quartz Job依賴(lài)注入使用詳解

一、問(wèn)題描述:

使用Spring整合quartz實(shí)現(xiàn)動(dòng)態(tài)任務(wù)時(shí),想在job定時(shí)任務(wù)中使用某個(gè)service時(shí),直接通過(guò)加注解@Component、@Autowired是不能注入的,獲取的對(duì)象為Null。如下面的代碼:

@Component 
@PersistJobDataAfterExecution 
@DisallowConcurrentExecution 
public class TicketSalePriceLessThanLowestPriceJob implements Job{ 
 
  @Autowired 
  private XxxService xxxService; 
 
} 

 二、解決方案:

1、新增一個(gè)自定義類(lèi)(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 {  
    //調(diào)用父類(lèi)的方法  
    Object jobInstance = super.createJobInstance(bundle);  
    //進(jìn)行注入  
    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> 
 

完整代碼如下:

<!-- 定時(shí)任務(wù)配置 start --> 
  <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
    <property name="dataSource" ref="dataSource"></property>   
    <!--可選,QuartzScheduler 啟動(dòng)時(shí)更新己存在的Job,這樣就不用每次修改targetObject后刪除qrtz_job_details表對(duì)應(yīng)記錄了 -->    
    <property name="overwriteExistingJobs" value="true" />    
     <!--必須的,QuartzScheduler 延時(shí)啟動(dòng),應(yīng)用啟動(dòng)完后 QuartzScheduler 再啟動(dòng) -->   
    <property name="startupDelay" value="10" />   
    <!-- 設(shè)置自動(dòng)啟動(dòng) -->   
    <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> 
  <!-- 定時(shí)任務(wù)配置 end --> 

4、然后就可以在Job任務(wù)類(lèi)使用@Autowired注入service。

如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論