原文: https://howtodoinjava.com/spring-batch/spring-beans-in-quartz-job/

默认情况下,Quartz 无法识别在applicationContext.xml或带有@Bean注解的 SpringBean。 如果尝试以 Quartz JobQuartzJobBean@Autowired这些 bean,您将得到NullPointerException

将 Spring 上下文注入QuartzJobBean

解决方案是将 Spring 的ApplicationContext实例注入到org.quartz.SchedulerContext中,该实例可通过executeInternal()方法的org.quartz.JobExecutionContext参数使用。

  1. ApplicationContext注入SchedulerContext


这是典型的SchedulerFactoryBean bean 条目。 使用setApplicationContextSchedulerContextKey()方法。 此方法设置要在SchedulerContext中公开的ApplicationContext引用的键。

  1. @Bean
  2. public SchedulerFactoryBean schedulerFactoryBean() throws IOException, SchedulerException
  3. {
  4. SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
  5. scheduler.setTriggers(jobOneTrigger(), jobTwoTrigger());
  6. scheduler.setQuartzProperties(quartzProperties());
  7. scheduler.setJobDetails(jobOneDetail(), jobTwoDetail());
  8. scheduler.setApplicationContextSchedulerContextKey("applicationContext");
  9. return scheduler;
  10. }
  1. 在 Quartz QuartzJobBean 中访问注入 bean


现在,您需要做的就是 – 获得applicationContext参考,并根据需要开始获取 bean。
CustomQuartzJob.java

  1. import org.quartz.JobExecutionContext;
  2. import org.quartz.JobExecutionException;
  3. import org.springframework.batch.core.Job;
  4. import org.springframework.batch.core.JobParameters;
  5. import org.springframework.batch.core.JobParametersBuilder;
  6. import org.springframework.batch.core.configuration.JobLocator;
  7. import org.springframework.batch.core.launch.JobLauncher;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.scheduling.quartz.QuartzJobBean;
  10. public class CustomQuartzJob extends QuartzJobBean {
  11. private String jobName;
  12. private JobLauncher jobLauncher;
  13. private JobLocator jobLocator;
  14. public String getJobName() {
  15. return jobName;
  16. }
  17. public void setJobName(String jobName) {
  18. this.jobName = jobName;
  19. }
  20. @Override
  21. protected void executeInternal(JobExecutionContext context) throws JobExecutionException
  22. {
  23. try
  24. {
  25. ApplicationContext applicationContext = (ApplicationContext)
  26. context.getScheduler().getContext().get("applicationContext");
  27. jobLocator = (JobLocator) applicationContext.getBean(JobLocator.class);
  28. jobLauncher = (JobLauncher) applicationContext.getBean(JobLauncher.class);
  29. Job job = jobLocator.getJob(jobName);
  30. JobParameters params = new JobParametersBuilder()
  31. .addString("JobID", String.valueOf(System.currentTimeMillis()))
  32. .toJobParameters();
  33. jobLauncher.run(job, params);
  34. }
  35. catch (Exception e)
  36. {
  37. e.printStackTrace();
  38. }
  39. }
  40. }

现在,当您运行 Quartz 作业时,将通过executeInternal()方法获得jobLocatorjobLauncher实例。

将我的问题放在评论部分。

学习愉快!