当Quartz要注入Spring Bean对象时,会报错,因为Job对象不是Spring进行管理的,当job对象中注入Spring Bean会产生空指针异常 即无法注入
解决办法:
写一个JobFactory ,在ApplicationContext 中配置jobFactory,由JobFactory生成job时候,自动注入Spring Bean对象
1 @Service("jobFactory") 2 public class JobFactory extends AdaptableJobFactory { 3 4 @Autowired 5 private AutowireCapableBeanFactory capableBeanFactory; 6 7 @Override 8 protected Object createJobInstance(TriggerFiredBundle bundle) 9 throws Exception { 10 Object jobInstance = super.createJobInstance(bundle); 11 capableBeanFactory.autowireBean(jobInstance); 12 return jobInstance; 13 } 14 }
然后在spring配置文件中配置
1 <bean id="myJobFactory" class="com.xqc.XXX.jobs.common.CustomJobFactory"></bean> 2 3 <!--
<bean id="executor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> 4 线程池维护线程的最少数量 5 <property name="corePoolSize" value="22" /> 6 允许的空闲时间 7 <property name="keepAliveSeconds" value="1000" /> 8 线程池维护线程的最大数量 9 <property name="maxPoolSize" value="44" /> 10 缓存队列 11 <property name="queueCapacity" value="88" /> 12 对拒绝task的处理策略 13 <property name="rejectedExecutionHandler"> 14 <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" /> 15 </property> 16 </bean>
--> 17 <bean name="quartzScheduler" 18 class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 19 <property name="jobFactory" ref="myJobFactory"/> 20 <!--
<property name="quartzProperties"> 21 <props> 22 主要是这个参数 23 <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop> 24 </props> 25 </property>
--> 26 <!-- <property name="taskExecutor" ref="executor" /> --> 27 <!-- triggers已放置到数据库中配置 --> 28 <!-- <property name="triggers"> 29 <list> 30 <ref bean="threadMonitor_CronTrigger"/> 31 <ref bean="tabledepathJob_CronTrigger"/> 32 <ref bean="log2MongoDbCronTrigger"></ref> 33 <ref bean="mq2Db_cfps_CronTrigger"/> 34 <ref bean="mq2Db_dyncgo_CronTrigger"/> 35 <ref bean="mq2Db_dynhgh_CronTrigger"/> 36 <ref bean="mq2Db_dynkwe_CronTrigger"/> 37 <ref bean="mq2Db_dynngb_CronTrigger"/> 38 <ref bean="mq2Db_dynszx_CronTrigger"/> 39 <ref bean="mq2Db_lsc_CronTrigger"/> 40 <ref bean="mq2Db_lst_CronTrigger"/> 41 <ref bean="mq2DbJob_cfps2cargos_CronTrigger"/> 42 43 <ref bean="task1Trigger"/> 44 </list> 45 </property>
--> 46 <property name="waitForJobsToCompleteOnShutdown" value="true"></property> 47 <property name="configLocation" value="classpath:system.properties"></property> 48 </bean>