作业参数通常用于在同一作业的不同实例之间变化的属性(通常用于识别作业实例)。在您的情况下,所有作业实例的作业名称都相同,因此我认为系统属性比作业参数更合适。这是一个简单的例子:
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableBatchProcessing
public class MyJobConfig {
@Bean
public Job job(JobBuilderFactory jobs, StepBuilderFactory steps,
@Value("${jobName:myDefaultJobName}") String jobName) {
return jobs.get(jobName)
.start(steps.get("step")
.tasklet((contribution, chunkContext) -> {
System.out.println("hello world");
return RepeatStatus.FINISHED;
})
.build())
.build();
}
public static void main(String[] args) throws Exception {
System.setProperty("jobName", "foo");
ApplicationContext context = new AnnotationConfigApplicationContext(MyJobConfig.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job job = context.getBean(Job.class);
jobLauncher.run(job, new JobParameters());
}
}
打印出来:
[main] INFO org.springframework.batch.core.launch.support.SimpleJobLauncher - Job: [SimpleJob: [name=foo]] launched with the following parameters: [{}]
[main] INFO org.springframework.batch.core.job.SimpleStepHandler - Executing step: [step]
hello world
[main] INFO org.springframework.batch.core.step.AbstractStep - Step: [step] executed in 31ms
[main] INFO org.springframework.batch.core.launch.support.SimpleJobLauncher - Job: [SimpleJob: [name=foo]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 57ms
您可以在使用-DjobName=dynamicJobName 启动作业时动态传递作业名称
编辑:添加如何从网络控制器启动作业的示例
@RestController
public class JobLaunchingController {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private ApplicationContext context;
@RequestMapping(value = "/", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.ACCEPTED)
public void launch(@RequestParam("jobName") String jobName) throws Exception {
Job job = context.getBean(jobName, Job.class);
jobLauncher.run(job, new JobParameters());
}
}