原文: https://howtodoinjava.com/spring-batch/spring-beans-in-quartz-job/
默认情况下,Quartz 无法识别在applicationContext.xml
或带有@Bean
注解的 SpringBean。 如果尝试以 Quartz Job
或QuartzJobBean
来@Autowired
这些 bean,您将得到NullPointerException
。
将 Spring 上下文注入QuartzJobBean
解决方案是将 Spring 的ApplicationContext
实例注入到org.quartz.SchedulerContext
中,该实例可通过executeInternal()
方法的org.quartz.JobExecutionContext
参数使用。
这是典型的SchedulerFactoryBean
bean 条目。 使用setApplicationContextSchedulerContextKey()
方法。 此方法设置要在SchedulerContext
中公开的ApplicationContext
引用的键。
@Bean
public SchedulerFactoryBean schedulerFactoryBean() throws IOException, SchedulerException
{
SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
scheduler.setTriggers(jobOneTrigger(), jobTwoTrigger());
scheduler.setQuartzProperties(quartzProperties());
scheduler.setJobDetails(jobOneDetail(), jobTwoDetail());
scheduler.setApplicationContextSchedulerContextKey("applicationContext");
return scheduler;
}
现在,您需要做的就是 – 获得applicationContext
参考,并根据需要开始获取 bean。
CustomQuartzJob.java
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.configuration.JobLocator;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class CustomQuartzJob extends QuartzJobBean {
private String jobName;
private JobLauncher jobLauncher;
private JobLocator jobLocator;
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException
{
try
{
ApplicationContext applicationContext = (ApplicationContext)
context.getScheduler().getContext().get("applicationContext");
jobLocator = (JobLocator) applicationContext.getBean(JobLocator.class);
jobLauncher = (JobLauncher) applicationContext.getBean(JobLauncher.class);
Job job = jobLocator.getJob(jobName);
JobParameters params = new JobParametersBuilder()
.addString("JobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();
jobLauncher.run(job, params);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
现在,当您运行 Quartz 作业时,将通过executeInternal()
方法获得jobLocator
和jobLauncher
实例。
将我的问题放在评论部分。
学习愉快!