默认情况下,quartz不会识别在注释中配置applicationContext.xml或使用@Bean注释配置的spring bean 。如果您尝试@Autowired这些豆类在石英Job或者QuartzJobBean,你会得到NullPointerException

向QuartzJobBean注入Spring上下文

解决方案是使用参数to 方法将Spring的ApplicationContext实例注入org.quartz.SchedulerContext其中。org.quartz.JobExecutionContextexecuteInternal()

  1. 将applicationContext注入SchedulerContext
    这是典型的SchedulerFactoryBeanbean入口。使用setApplicationContextSchedulerContextKey()方法。此方法将ApplicationContext引用的键设置为公开SchedulerContext

@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;
}

访问在Quartz QuartzJobBean中注入bean

现在,您需要做的就是 - 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作业时,您将获得方法中的jobLocatorjobLauncher实例executeInternal()