Quartz和Spring Boot的问题

时间:2018-06-30 15:56:44

标签: java spring spring-boot quartz-scheduler

所以我遇到了技术难题,需要帮助。

一个大型项目正在使用Quartz调度程序来调度一项工作,该工作每天晚上9点运行。
计划的Job,但是需要从属性文件中读取值,使用自动装配等获取一些bean。

当我使用@Autowired和@Value批注时,我发现这些值为空。

问题是Quartz在弹簧容器之外使用newJob()创建JobDetail对象。如下面的代码所示。

JobKey jobKey = new JobKey("NightJob", "9-PM Job");
JobDetail jobDetail = newJob(NightJob.class).withIdentity(jobKey)
                     .usingJobData("Job-Id", "1")
                     .build();

包裹jobDetail的{​​{1}}对象因此无法使用spring访问属性文件或bean。

这是我的NightJob

NightJob

我扫描了堆栈溢出并列出了几种解决方案。我还仔细阅读了这些评论,并列出了最重要的反对意见。

  

建议1:由于其与Spring Boot的良好集成,请摆脱Quartz并使用Spring Batch

     

计数器参数1:对于简单任务而言,Spring Batch过于强大。使用@Scheduled

     

建议2:使用spring提供的@Scheduled注释和cron表达式

     

计数器参数2:如果删除Quartz,则您的应用程序将来将无法就绪。将来可能需要复杂的计划

     

建议3 :使用Spring界面ApplicationContextAware。

     

计数器参数3:很多其他代码。击败了Spring Boot的简单概念

Spring Boot中是否有一种更简单的方法来访问实现Quartz作业的类中的属性文件值和自动装配对象(在这种情况下,为public class NightJob implements Job{ //@Value to read from property file; here //@Autowired to use some beans; here @Override public void execute(JobExecutionContext context) throws JobExecutionException{ } } 类)

1 个答案:

答案 0 :(得分:2)

如评论中所述,Spring通过提供setter方法来支持将Bean注入Quartz作业:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-quartz.html