使用SpringBatch启动时发现会自动启动配置的job,由此观察了一下启动的过程
启动时会加载BatchAutoConfiguration,针对启动的配置
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(
prefix = "spring.batch.job",
name = {"enabled"},
havingValue = "true",
matchIfMissing = true
)
public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer, JobRepository jobRepository, BatchProperties properties) {
JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(jobLauncher, jobExplorer, jobRepository);
String jobNames = properties.getJob().getNames();
if (StringUtils.hasText(jobNames)) {
runner.setJobNames(jobNames);
}
return runner;
}
首先如果想关闭自动启动
在 application.properties文件加上如下配置:
项目启动时不调用 Job
spring.batch.job.enabled = false
项目启动时调用 Job
spring.batch.job.enabled = true
如果是true,会执行JobLauncherCommandLineRunner中的run方法,之后会调用
protected void launchJobFromProperties(Properties properties) throws JobExecutionException {
JobParameters jobParameters = this.converter.getJobParameters(properties);
this.executeLocalJobs(jobParameters);
this.executeRegisteredJobs(jobParameters);
}
这些方法中有
this.execute(job, jobParameters);
调用JobLauncher.run方法,其中SimpleJobLauncher去实现的run方法
//查询上次未执行完的job继续执行,如果执行完成则也不再执行
JobExecution lastExecution = this.jobRepository.getLastJobExecution(job.getName(), jobParameters);
//如果没有执行完成的job会创建一个新的执行
final JobExecution jobExecution = this.jobRepository.createJobExecution(job.getName(), jobParameters);
JobInstance jobInstance = this.jobInstanceDao.getJobInstance(jobName, jobParameters);
ExecutionContext executionContext;
if (jobInstance == null) {
jobInstance = this.jobInstanceDao.createJobInstance(jobName, jobParameters);
executionContext = new ExecutionContext();
}