一般情况下,quartz的job中使用autowired注解注入的对象为空,这时候我们就要使用spring-quartz提供的AdaptableJobFactory类。
自定义一个类:
- public class JobFactory extends AdaptableJobFactory {
- @Autowired
- private AutowireCapableBeanFactory capableBeanFactory;
- @Override
- protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
- //调用父类的方法
- Object jobInstance = super.createJobInstance(bundle);
- //进行注入
- capableBeanFactory.autowireBean(jobInstance);
- return jobInstance;
- }
- }
然后在spring中配置:
- <!-- 定时任务的factorybean,配置其他config -->
- <bean id="jobFactory" class="com.xx.job.JobFactory"></bean>
- <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
- <property name="jobFactory" ref="jobFactory"></property>
- </bean>
这时候,我们在定义类继承job的时候,就可以使用autowired注入service对象了:
- public class Test1Job implements Job {
- public final Logger log = Logger.getLogger(this.getClass());
- @Autowired
- private JobTaskService jobTaskService;
- public void execute(JobExecutionContext context) throws JobExecutionException {
- //更新上一次执行时间和下一次计划执行时间
- Date nextProcessTime = context.getNextFireTime();
- ScheduleJob job = (ScheduleJob) context.getJobDetail().getJobDataMap().get("scheduleJob");
- job.setNextProcessTime(nextProcessTime);
- jobTaskService.updateTaskByJobName(job);
- //业务逻辑
- System.out.println("22222222222222222222:");
- }
- }