代码之家  ›  专栏  ›  技术社区  ›  SamwellTarly

石英和弹簧套问题

  •  1
  • SamwellTarly  · 技术社区  · 6 年前

    所以我有一个技术难题需要帮助。

    一个大型项目正在使用一个石英调度器来安排每天晚上9点运行的作业。
    但是,调度的作业需要从属性文件中读取值、使用自动连接获取一些bean等。

    当我使用@autowired和@value注释时,发现值为空。

    问题是quartz使用 newJob() 在弹簧容器外面。如下代码所示。

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

    这个 jobDetail 包裹的物体 NightJob 因此无法使用spring访问属性文件或bean。

    这是我的 夜班

    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: 去掉石英,使用弹簧批,因为它与弹簧套很好的结合

    反参数1: 对于简单的任务来说,spring批处理是过度的。使用@scheduled

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

    反论点2: 如果删除quartz,您的应用程序将无法在将来准备就绪。未来可能需要复杂的调度

    建议3: 使用Spring接口applicationContextAware。

    反论点3: 很多附加代码。击败了简单易用的弹簧靴概念

    在spring boot中,有没有一种更简单的方法来访问实现quartz作业的类中的属性文件值和autowire对象(在这种情况下, 夜班 类别)

    1 回复  |  直到 6 年前
        1
  •  2
  •   Marcus K.    6 年前

    如注释中所述,spring通过提供setter方法支持向quartz作业中注入bean: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-quartz.html