Spring Boot集成Quartz注入Spring管理的类的方法
在SpringBoot中使用Quartz时,在JOB中一般需要引用Spring管理的Bean,通过定义JobFactory实现自动注入。
Spring有自己的Schedule定时任务,在Springboot中使用的时候,不能动态管理JOB,于是就使用Quartz来实现。
在SpringBoot中配置Quartz:
importjava.io.IOException; importjava.util.Properties; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.beans.factory.config.PropertiesFactoryBean; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.core.io.ClassPathResource; importorg.springframework.scheduling.annotation.EnableScheduling; importorg.springframework.scheduling.quartz.SchedulerFactoryBean; @Configuration @EnableScheduling publicclassQuartzSchedule{ @Autowired privateMyJobFactorymyJobFactory; @Bean publicSchedulerFactoryBeanschedulerFactoryBean()throwsIOException{ SchedulerFactoryBeanfactory=newSchedulerFactoryBean(); factory.setOverwriteExistingJobs(true); //延时启动 factory.setStartupDelay(20); //加载quartz数据源配置 factory.setQuartzProperties(quartzProperties()); //自定义JobFactory,用于Spring注入 factory.setJobFactory(myJobFactory); returnfactory; } /** *加载quartz数据源配置 * *@return *@throwsIOException */ @Bean publicPropertiesquartzProperties()throwsIOException{ PropertiesFactoryBeanpropertiesFactoryBean=newPropertiesFactoryBean(); propertiesFactoryBean.setLocation(newClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); returnpropertiesFactoryBean.getObject(); } }
为了在JOB中使用Spring管理的Bean,需要重新定义一个JobFactory:
@Component publicclassMyJobFactoryextendsAdaptableJobFactory{ @Autowired privateAutowireCapableBeanFactorycapableBeanFactory; @Override protectedObjectcreateJobInstance(TriggerFiredBundlebundle)throwsException{ //调用父类的方法 ObjectjobInstance=super.createJobInstance(bundle); //进行注入 capableBeanFactory.autowireBean(jobInstance); returnjobInstance; } }
然后在JOB中就可以使用Spring管理的Bean了
publicclassMyJobimplementsJob,Serializable{ privatestaticfinallongserialVersionUID=1L; privateLoggerlogger=LoggerFactory.getLogger(this.getClass()); @Autowired privateSomeServicesomeService; @Override publicvoidexecute(JobExecutionContextcontext)throwsJobExecutionException{ someService.doSomething(); } }
下面代码是创建JOB:
JobDetailjobDetail=JobBuilder.newJob(((Job)Class.forName(job.getClazz()).newInstance()).getClass()) .withIdentity(job.getJobName(),job.getJobGroup()).build(); jobDetail.getJobDataMap().put("extdata",job.getExtData()); //表达式调度构建器 CronScheduleBuilderscheduleBuilder=CronScheduleBuilder.cronSchedule(job.getCronExpression()) .withMisfireHandlingInstructionDoNothing(); //构建一个trigger TriggerBuildertriggerBuilder=TriggerBuilder.newTrigger().withIdentity(triggerKey) .withSchedule(scheduleBuilder); if(job.getStartTime()!=null){ triggerBuilder.startAt(job.getStartTime()); } if(job.getEndTime()!=null){ triggerBuilder.endAt(job.getEndTime()); } CronTriggertrigger=triggerBuilder.build(); scheduler.scheduleJob(jobDetail,trigger);//注入到管理类
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。