quartz整合Spring注入Service时空指针异常问题解决

时间:2024-11-03 07:08:08

利用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 
		class="">
		<property name="jobClass" value="" />
		<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 
		class="">
		<property name="jobDetail" ref="complexJobDetail" />
		<property name="cronExpression" value="0 06 23 * * ? " />
	</bean>
	<bean class="">
		<property name="jobDetails">
			<list>
				<ref bean="complexJobDetail" />
			</list>
		</property>
		<property name="triggers">
			<list>
				<ref bean="cronTrigger" />
			</list>
		</property>
	</bean>
	<!-- 工作的bean -->
	<bean  class="" />

public class GenerateBusJob extends QuartzJobBean{
	
	@Autowired
	ScheduleService scheduleService;
	public void query(){
		
		();
	}

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		scheduleService= (ScheduleService) ()
                .getJobDataMap().get("scheduleService");
		query();
	}
}