spring-boot-starter-quartz 实现 job 与扩展 QuartzJobBean

sou*_*ung 4 jobs spring-boot quartz

我在我的一个项目中使用 Quartz Scheduler。创建 Quartz 作业主要有两种方式:

  1. 实现org.quartz.Job
  2. 扩展org.springframework.scheduling.quartz.QuartzJobBean(实现 org.quartz.Job 类)

QuartzJobBean javadoc 的最后一部分令人困惑:

* Note that the preferred way to apply dependency injection to Job instances is via a JobFactory: 
that is, to specify SpringBeanJobFactory as Quartz JobFactory (typically via
SchedulerFactoryBean.setJobFactory SchedulerFactoryBean's "jobFactory" property}). 
This allows to implement dependency-injected Quartz Jobs without a dependency on Spring base classes.*
Run Code Online (Sandbox Code Playgroud)

对于纯粹的 Spring(或 SpringBoot)使用,我认为最好扩展 QuartzJobBean。我是对的?

Ste*_*eve 7

首先,由于 aQuartzJobBean是 a Job,任何接受 a 的 API 调用Job都会接受 a QuartzJobBean,但反之则不然。因此,如果您需要一个QuartzJobBean,因为某些 API 调用希望您传递一个,那么这就是您的答案。

Otherwise, the answer depends on if you want to make use of (and be tied to) the functionality provided by QuartzJobBean. If you look at the source code for that class, you'll see that the sole gain in subclassing QuartzJobBean over implementing Job, is that QuartzJobBean performs this logic before passing control to your code:

    try {
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
        MutablePropertyValues pvs = new MutablePropertyValues();
        pvs.addPropertyValues(context.getScheduler().getContext());
        pvs.addPropertyValues(context.getMergedJobDataMap());
        bw.setPropertyValues(pvs, true);
    }
    catch (SchedulerException ex) {
        throw new JobExecutionException(ex);
    }
Run Code Online (Sandbox Code Playgroud)

So if you extend the QuartzJobBean class and implement the executeInternal method, this code runs before your code. If you implement the Job class and the execute method, it does not. That's the only difference between the two approaches in terms of what actually happens when your job runs.

So to answer your question, ask yourself "do I want to take advantage of the above code?". If the answer is Yes, then extend QuartzJobBean to take advantage of that functionality. If you don't need this added functionality, don't want it, and/or don't want to be locked into the dependencies implied by the above code, then you should implement Job to avoid this code and its dependencies. My personal approach would be to implement Job unless I had some reason to extend QuartzJobBean instead.