springboot中启动:
启动类中的run方法往下运行会调用callRunner方法:
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
Iterator var4 = (new LinkedHashSet(runners)).iterator();
while(var4.hasNext()) {
Object runner = var4.next();
if (runner instanceof ApplicationRunner) {
this.callRunner((ApplicationRunner)runner, args);
}
if (runner instanceof CommandLineRunner) {
this.callRunner((CommandLineRunner)runner, args);
}
}
}
这里会获取到SpringBatch 自动配置, BatchAutoConfiguration中注册的CommandLineRunner bean。进而执行。
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(
prefix = "spring.batch.job",
name = {"enabled"},
havingValue = "true",
matchIfMissing = true
)
public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer, JobRepository jobRepository) {
JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(jobLauncher, jobExplorer, jobRepository);
String jobNames = this.properties.getJob().getNames();
if (StringUtils.hasText(jobNames)) {
runner.setJobNames(jobNames);
}
return runner;
}
如果配置文件中没有配置:
spring.batch.job.enabled = false
job任务会在springboot启动时执行
退出:
@SpringBootApplication
public class MainClass {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(MainClass.class);
int exitCode = SpringApplication.exit(context );
System.exit(exitCode);
}
}
参考JobLauncherCommandLineRunner 可知,在execute方法中发布了ApplicationEvent
protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException, JobParametersNotFoundException {
JobParameters parameters = this.getNextJobParameters(job, jobParameters);
JobExecution execution = this.jobLauncher.run(job, parameters);
if (this.publisher != null) {
this.publisher.publishEvent(new JobExecutionEvent(execution));
}
}
public void onApplicationEvent(JobExecutionEvent event) {
this.executions.add(event.getJobExecution());
}
JobExecutionEvent 事件由JobExecutionExitCodeGenerator监听。并以此生成退出码。
public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) {
Assert.notNull(context, "Context must not be null");
byte exitCode = 0;
int exitCode;
try {
try {
ExitCodeGenerators generators = new ExitCodeGenerators();
Collection<ExitCodeGenerator> beans = context.getBeansOfType(ExitCodeGenerator.class).values();
generators.addAll(exitCodeGenerators);
generators.addAll(beans);
exitCode = generators.getExitCode();
if (exitCode != 0) {
context.publishEvent(new ExitCodeEvent(context, exitCode));
}
} finally {
close(context);
}
} catch (Exception var9) {
var9.printStackTrace();
exitCode = exitCode != 0 ? exitCode : 1;
}
return exitCode;
}