ITeye博客

quartz的job中注入spring对象!(转帖)

BreakingBad · 2016-09-18 18:48 · Quartz · 编程语言 · quartz · Spring · job · dependency · Markdown

转帖地址:http://blog.csdn.net/u012572955/article/details/51656270

一般情况下,quartz的job中使用autowired注解注入的对象为空,这时候我们就要使用spring-quartz提供的AdaptableJobFactory类。

自定义一个类:

[java] view plain copy

 

 在CODE上查看代码片派生到我的代码片

  1. public class JobFactory extends AdaptableJobFactory {
  2. @Autowired
  3. private AutowireCapableBeanFactory capableBeanFactory;
  4. @Override
  5. protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
  6. //调用父类的方法
  7. Object jobInstance = super.createJobInstance(bundle);
  8. //进行注入
  9. capableBeanFactory.autowireBean(jobInstance);
  10. return jobInstance;
  11. }
  12. }

然后在spring中配置:

 

 

[html] view plain copy

 

 在CODE上查看代码片派生到我的代码片

  1. <!-- 定时任务的factorybean,配置其他config -->
  2. <bean id="jobFactory" class="com.xx.job.JobFactory"></bean>
  3. <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  4. <property name="jobFactory" ref="jobFactory"></property>
  5. </bean>

这时候,我们在定义类继承job的时候,就可以使用autowired注入service对象了:

 

 

[java] view plain copy

 

 在CODE上查看代码片派生到我的代码片

  1. public class Test1Job implements Job {
  2. public final Logger log = Logger.getLogger(this.getClass());
  3. @Autowired
  4. private JobTaskService jobTaskService;
  5. public void execute(JobExecutionContext context) throws JobExecutionException {
  6. //更新上一次执行时间和下一次计划执行时间
  7. Date nextProcessTime = context.getNextFireTime();
  8. ScheduleJob job = (ScheduleJob) context.getJobDetail().getJobDataMap().get("scheduleJob");
  9. job.setNextProcessTime(nextProcessTime);
  10. jobTaskService.updateTaskByJobName(job);
  11. //业务逻辑
  12. System.out.println("22222222222222222222:");
  13. }
  14. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。