利用Quartz可以实现定时任务,但在跟Spring整合后,直接在Job中注解方式注入Service后运行却报空指针异常。
原因是Quartz初始化是自己的JobContext,不同于Spring的ApplicationContext,所以无法直接注入。必须通过JobDetail中的
jobDataAsMap传<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">入。</span>
具体代码如下:
<bean id="complexJobDetail"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.townbus.job.GenerateBusJob" />
<property name="durability" value="true" />
<property name="jobDataAsMap"><!-- 非常重要,用来向JobDetail传参 -->
<map>
<entry key ="scheduleService" value-ref="scheduleService"/>
<entry key="timeout" value="5" />
</map>
</property>
</bean>
<bean id="cronTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="complexJobDetail" />
<property name="cronExpression" value="0 06 23 * * ? " />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="complexJobDetail" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
<!-- 工作的bean -->
<bean id="generateBusJob" class="com.townbus.job.GenerateBusJob" />
public class GenerateBusJob extends QuartzJobBean{
@Autowired
ScheduleService scheduleService;
public void query(){
scheduleService.generateBus();
}
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
scheduleService= (ScheduleService) context.getJobDetail()
.getJobDataMap().get("scheduleService");
query();
}
}