欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring/Spring boot正确集成Quartz及解决@Autowired失效问题

程序员文章站 2024-01-29 22:05:58
周五检查以前 集成 项目的时候,发现配置错误,因此通过阅读源码的方式,探索 正确集成 的方式. 问题发现 检查去年的项目代码,发现关于 的实现存在不合理的地方. (1) 项目依赖: (2) 问题代码: (3) 提炼问题: 以上代码存在错误的原因是, 添加 注解,表示其是 容器中的 类. 然而 在创建 ......

周五检查以前spring boot集成quartz项目的时候,发现配置错误,因此通过阅读源码的方式,探索spring正确集成quartz的方式.

问题发现

检查去年的项目代码,发现关于quartzjobbean的实现存在不合理的地方.

(1) 项目依赖:

    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>2.1.0.release</version>
        <relativepath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupid>org.quartz-scheduler</groupid>
            <artifactid>quartz</artifactid>
        </dependency>
    </dependencies>

(2) 问题代码:

@component
public class unprocessedtaskjob extends quartzjobbean {

    private taskmapper taskmapper;

    @autowired
    public unprocessedtaskjob(taskmapper taskmapper){
        this.taskmapper = taskmapper;
    }
}

private jobdetail generateunprocessedjobdetail(task task) {
    jobdatamap jobdatamap = new jobdatamap();
    jobdatamap.put(unprocessedtaskjob.task_id, task.getid());
    return jobbuilder.newjob(unprocessedtaskjob.class)
            .withidentity(unprocessedtaskjob.unprocessed_task_key_prefix + task.getid(), unprocessedtaskjob.unprocessed_task_job_group)
            .usingjobdata(jobdatamap)
            .storedurably()
            .build();
    }

(3) 提炼问题:

以上代码存在错误的原因是,unprocessedtaskjob添加@component注解,表示其是spring ioc容器中的单例类.
然而quartz在创建job是通过相应的quartz job beanclass反射创建相应的job.也就是说,每次创建新的job时,都会生成相应的job实例.从而,这与unprocessedtaskjob单例相冲突.
查看代码提交记录,原因是当时认为不添加@component注解,则无法通过@autowired引入由spring ioc托管的taskmapper实例,即无法实现依赖注入.

然而令人感到奇怪的是,当我在开发环境去除了unprocessedtaskjob@component注解之后,运行程序后发现taskmapper实例依然可以注入到job中,程序正常运行...

spring托管quartz

代码分析

网上搜索spring托管quartz的文章,大多数都是spring mvc项目,集中于如何解决在job实现类中通过@autowired实现spring依赖注入.
网上大多实现均依赖springbeanjobfactory去实现springquartz的集成.

/**
 * subclass of {@link adaptablejobfactory} that also supports spring-style
 * dependency injection on bean properties. this is essentially the direct
 * equivalent of spring's {@link quartzjobbean} in the shape of a quartz
 * {@link org.quartz.spi.jobfactory}.
 *
 * <p>applies scheduler context, job data map and trigger data map entries
 * as bean property values. if no matching bean property is found, the entry
 * is by default simply ignored. this is analogous to quartzjobbean's behavior.
 *
 * <p>compatible with quartz 2.1.4 and higher, as of spring 4.1.
 *
 * @author juergen hoeller
 * @since 2.0
 * @see schedulerfactorybean#setjobfactory
 * @see quartzjobbean
 */
public class springbeanjobfactory extends adaptablejobfactory
        implements applicationcontextaware, schedulercontextaware {
}

/**
 * {@link jobfactory} implementation that supports {@link java.lang.runnable}
 * objects as well as standard quartz {@link org.quartz.job} instances.
 *
 * <p>compatible with quartz 2.1.4 and higher, as of spring 4.1.
 *
 * @author juergen hoeller
 * @since 2.0
 * @see delegatingjob
 * @see #adaptjob(object)
 */
public class adaptablejobfactory implements jobfactory {
}

通过上述代码以及注释可以发现:

(1) adaptablejobfactory实现了jobfactory接口,可以藉此创建标准的quartz实例(仅限于quartz 2.1.4及以上版本);

(2) springbeanjobfactory继承于adaptablejobfactory,从而实现对quartz封装实例的属性依赖注入.

(3) springbeanjobfactory实现了applicationcontextaware以及schedulercontextaware接口(quartz任务调度上下文),因此可以在创建job bean的时候注入applicationcontex以及schedulercontext.

tips:
以上代码基于spring 5.1.8版本.
spring 4.1.0版本, springbeanjobfactory的实现如以下代码所示:

public class springbeanjobfactory extends adaptablejobfactory
    implements schedulercontextaware{

    // 具体代码省略
}

因此,在早期的spring项目中,需要封装springbeanjobfactory并实现applicationcontextaware接口(惊不惊喜?).

spring老版本解决方案

基于老版本spring给出解决spring集成quartz解决方案.
解决方案由第三十九章:基于springboot & quartz完成定时任务分布式单节点持久化提供(大神的系列文章质量很棒).

@configuration
public class quartzconfiguration
{
    /**
     * 继承org.springframework.scheduling.quartz.springbeanjobfactory
     * 实现任务实例化方式
     */
    public static class autowiringspringbeanjobfactory extends springbeanjobfactory implements
            applicationcontextaware {

        private transient autowirecapablebeanfactory beanfactory;

        @override
        public void setapplicationcontext(final applicationcontext context) {
            beanfactory = context.getautowirecapablebeanfactory();
        }

        /**
         * 将job实例交给spring ioc托管
         * 我们在job实例实现类内可以直接使用spring注入的调用被spring ioc管理的实例
         * @param bundle
         * @return
         * @throws exception
         */
        @override
        protected object createjobinstance(final triggerfiredbundle bundle) throws exception {
            final object job = super.createjobinstance(bundle);
            /**
             * 将job实例交付给spring ioc
             */
            beanfactory.autowirebean(job);
            return job;
        }
    }

    /**
     * 配置任务工厂实例
     * @param applicationcontext spring上下文实例
     * @return
     */
    @bean
    public jobfactory jobfactory(applicationcontext applicationcontext)
    {
        /**
         * 采用自定义任务工厂 整合spring实例来完成构建任务
         * see {@link autowiringspringbeanjobfactory}
         */
        autowiringspringbeanjobfactory jobfactory = new autowiringspringbeanjobfactory();
        jobfactory.setapplicationcontext(applicationcontext);
        return jobfactory;
    }

    /**
     * 配置任务调度器
     * 使用项目数据源作为quartz数据源
     * @param jobfactory 自定义配置任务工厂(其实就是autowiringspringbeanjobfactory)
     * @param datasource 数据源实例
     * @return
     * @throws exception
     */
    @bean(destroymethod = "destroy",autowire = autowire.no)
    public schedulerfactorybean schedulerfactorybean(jobfactory jobfactory, datasource datasource) throws exception
    {
        schedulerfactorybean schedulerfactorybean = new schedulerfactorybean();
        //将spring管理job自定义工厂交由调度器维护
        schedulerfactorybean.setjobfactory(jobfactory);
        //设置覆盖已存在的任务
        schedulerfactorybean.setoverwriteexistingjobs(true);
        //项目启动完成后,等待2秒后开始执行调度器初始化
        schedulerfactorybean.setstartupdelay(2);
        //设置调度器自动运行
        schedulerfactorybean.setautostartup(true);
        //设置数据源,使用与项目统一数据源
        schedulerfactorybean.setdatasource(datasource);
        //设置上下文spring bean name
        schedulerfactorybean.setapplicationcontextschedulercontextkey("applicationcontext");
        //设置配置文件位置
        schedulerfactorybean.setconfiglocation(new classpathresource("/quartz.properties"));
        return schedulerfactorybean;
    }
}

通过以上代码,就实现了由springbeanjobfactorycreatejobinstance创建job实例,并将生成的job实例交付由autowirecapablebeanfactory来托管.
schedulerfactorybean则设置诸如jobfactory(实际上是autowiringspringbeanjobfactory,内部封装了applicationcontext)以及datasource(数据源,如果不设置,则quartz默认使用ramjobstore).

ramjobstore优点是运行速度快,缺点则是调度任务无法持久化保存.

因此,我们可以在定时任务内部使用spring ioc@autowired等注解进行依赖注入.

spring新版本解决方案

(1) 解释

如果你使用spring boot,并且版本好大于2.0,则推荐使用spring-boot-starter-quartz.

    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-quartz</artifactid>
    </dependency>

auto-configuration support is now include for the quartz scheduler. we’ve also added a new spring-boot-starter-quartz starter pom.
you can use in-memory jobstores, or a full jdbc-based store. all jobdetail, calendar and trigger beans from your spring application context will be automatically registered with the scheduler.
for more details read the new “quartz scheduler” section of the reference documentation.

以上是spring-boot-starter-quartz的介绍,基于介绍可知,如果你没有关闭quartz的自动配置,则springboot会帮助你完成scheduler的自动化配置,诸如jobdetail/calendar/triggerbean会被自动注册至shceduler中.你可以在quartzjobbean中*的使用@autowired依赖注入注解.

其实,不引入spring-boot-starter-quartz,而仅仅导入org.quartz-scheduler,quartz的自动化配置依然会起效(这就是第一节问题分析中,去除@bean注解,程序依然正常运行原因,悲剧中万幸).

(2) 代码分析

/**
 * {@link enableautoconfiguration auto-configuration} for quartz scheduler.
 *
 * @author vedran pavic
 * @author stephane nicoll
 * @since 2.0.0
 */
@configuration
@conditionalonclass({ scheduler.class, schedulerfactorybean.class, platformtransactionmanager.class })
@enableconfigurationproperties(quartzproperties.class)
@autoconfigureafter({ datasourceautoconfiguration.class, hibernatejpaautoconfiguration.class })
public class quartzautoconfiguration{

    // 此处省略部分代码

    @bean
    @conditionalonmissingbean
    public schedulerfactorybean quartzscheduler() {
        // 因为新版本schedulerfactorybean已经实现applicationcontextaware接口
        // 因此相对于老版本spring解决方案中的autowiringspringbeanjobfactory进行封装
        schedulerfactorybean schedulerfactorybean = new schedulerfactorybean();
        springbeanjobfactory jobfactory = new springbeanjobfactory();
        // springbeanjobfactory中注入applicationcontext,为依赖注入创造条件
        jobfactory.setapplicationcontext(this.applicationcontext);
        // schedulerfactorybean中注入setjobfactory(注意此处没有配置datasource,datasource详见`jdbcstoretypeconfiguration`)
        // 以上这几个步骤,与老版本的spring解决方案类似
        schedulerfactorybean.setjobfactory(jobfactory);

        // 后续都是quartz的配置属性设置,不再叙述
        if (this.properties.getschedulername() != null) {
            schedulerfactorybean.setschedulername(this.properties.getschedulername());
        }
        schedulerfactorybean.setautostartup(this.properties.isautostartup());schedulerfactorybean.setstartupdelay((int) this.properties.getstartupdelay().getseconds());
        schedulerfactorybean.setwaitforjobstocompleteonshutdown(this.properties.iswaitforjobstocompleteonshutdown());
        schedulerfactorybean.setoverwriteexistingjobs(this.properties.isoverwriteexistingjobs());
        if (!this.properties.getproperties().isempty()) {
            schedulerfactorybean.setquartzproperties(asproperties(this.properties.getproperties()));
        }
        if (this.jobdetails != null && this.jobdetails.length > 0) {
            schedulerfactorybean.setjobdetails(this.jobdetails);
        }
        if (this.calendars != null && !this.calendars.isempty()) {
            schedulerfactorybean.setcalendars(this.calendars);
        }
        if (this.triggers != null && this.triggers.length > 0) {
            schedulerfactorybean.settriggers(this.triggers);
        }
        customize(schedulerfactorybean);
        return schedulerfactorybean;
    }

    @configuration
    @conditionalonsinglecandidate(datasource.class)
    protected static class jdbcstoretypeconfiguration {

        // 为quartz的持久化配置datasource,具体代码可以翻阅spring源码得到
    }
}

下面对springbeanjobfactory进行分析,它是生成job实例,以及进行依赖注入操作的关键类.

/**
 * subclass of {@link adaptablejobfactory} that also supports spring-style
 * dependency injection on bean properties. this is essentially the direct
 * equivalent of spring's {@link quartzjobbean} in the shape of a quartz
 * {@link org.quartz.spi.jobfactory}.
 *
 * <p>applies scheduler context, job data map and trigger data map entries
 * as bean property values. if no matching bean property is found, the entry
 * is by default simply ignored. this is analogous to quartzjobbean's behavior.
 *
 * <p>compatible with quartz 2.1.4 and higher, as of spring 4.1.
 *
 * @author juergen hoeller
 * @since 2.0
 * @see schedulerfactorybean#setjobfactory
 * @see quartzjobbean
 */
public class springbeanjobfactory extends adaptablejobfactory
        implements applicationcontextaware, schedulercontextaware {

    @nullable
    private string[] ignoredunknownproperties;

    @nullable
    private applicationcontext applicationcontext;

    @nullable
    private schedulercontext schedulercontext;

    /**
     * specify the unknown properties (not found in the bean) that should be ignored.
     * <p>default is {@code null}, indicating that all unknown properties
     * should be ignored. specify an empty array to throw an exception in case
     * of any unknown properties, or a list of property names that should be
     * ignored if there is no corresponding property found on the particular
     * job class (all other unknown properties will still trigger an exception).
     */
    public void setignoredunknownproperties(string... ignoredunknownproperties) {
        this.ignoredunknownproperties = ignoredunknownproperties;
    }

    @override
    public void setapplicationcontext(applicationcontext applicationcontext) {
        this.applicationcontext = applicationcontext;
    }

    @override
    public void setschedulercontext(schedulercontext schedulercontext) {
        this.schedulercontext = schedulercontext;
    }

    /**
     * create the job instance, populating it with property values taken
     * from the scheduler context, job data map and trigger data map.
     */
    @override
    protected object createjobinstance(triggerfiredbundle bundle) throws exception {
        // 创建job实例
        // (1) 包含applicationcontext,则通过autowirecapablebeanfactory()创建相应job实例,实现依赖注入
        // (2) 如果applicationcontext为空,则使用adaptablejobfactory创建相应的bean(无法实现依赖注入)
        object job = (this.applicationcontext != null ?
                        this.applicationcontext.getautowirecapablebeanfactory().createbean(
                            bundle.getjobdetail().getjobclass(), autowirecapablebeanfactory.autowire_constructor, false) :
                        super.createjobinstance(bundle));

        if (iseligibleforpropertypopulation(job)) {
            beanwrapper bw = propertyaccessorfactory.forbeanpropertyaccess(job);
            mutablepropertyvalues pvs = new mutablepropertyvalues();
            if (this.schedulercontext != null) {
                pvs.addpropertyvalues(this.schedulercontext);
            }
            pvs.addpropertyvalues(bundle.getjobdetail().getjobdatamap());
            pvs.addpropertyvalues(bundle.gettrigger().getjobdatamap());
            if (this.ignoredunknownproperties != null) {
                for (string propname : this.ignoredunknownproperties) {
                    if (pvs.contains(propname) && !bw.iswritableproperty(propname)) {
                        pvs.removepropertyvalue(propname);
                    }
                }
                bw.setpropertyvalues(pvs);
            }
            else {
                bw.setpropertyvalues(pvs, true);
            }
        }

        return job;
    }

    // 省略部分代码
}

/**
 * {@link jobfactory} implementation that supports {@link java.lang.runnable}
 * objects as well as standard quartz {@link org.quartz.job} instances.
 *
 * <p>compatible with quartz 2.1.4 and higher, as of spring 4.1.
 *
 * @author juergen hoeller
 * @since 2.0
 * @see delegatingjob
 * @see #adaptjob(object)
 */
public class adaptablejobfactory implements jobfactory {
    /**
     * create an instance of the specified job class.
     * <p>can be overridden to post-process the job instance.
     * @param bundle the triggerfiredbundle from which the jobdetail
     * and other info relating to the trigger firing can be obtained
     * @return the job instance
     * @throws exception if job instantiation failed
     */
    protected object createjobinstance(triggerfiredbundle bundle) throws exception {
        // 获取`quartzjobbean`的实现`class`,通过反射工具创建相应的类实例(自然无法注入spring托管的bean实例)
        class<?> jobclass = bundle.getjobdetail().getjobclass();
        return reflectionutils.accessibleconstructor(jobclass).newinstance();
    }
}

此处需要解释下autowirecapablebeanfactory的作用.
项目中,有部分实现并未与spring深度集成,因此其实例并未被spring容器管理.
然而,出于需要,这些并未被spring管理的bean需要引入spring容器中的bean.
此时,就需要通过实现autowirecapablebeanfactory,从而让spring实现依赖注入等功能.

希望能够通过上述解释以及代码分析,让你知晓如何在老版本以及新版本spring中正确集成quartz.
此外,spring boot的自动化配置能够解决绝大多数配置问题,但是在时间充裕的情况下,建议通过阅读源码等方式了解配置细节,从而做到更加的胸有成竹.

ps:
如果您觉得我的文章对您有帮助,可以扫码领取下红包或扫码支持(随意多少,一分钱都是爱),谢谢!

支付宝红包 支付宝 微信
Spring/Spring boot正确集成Quartz及解决@Autowired失效问题 Spring/Spring boot正确集成Quartz及解决@Autowired失效问题 Spring/Spring boot正确集成Quartz及解决@Autowired失效问题