1.You first disable automatic job start by specifying spring.batch.job.enabled=false
in application.properties
2.In your main class, do - ApplicationContext ctx = SpringApplication.run(SpringBatchMain.class, args);
assuming your main class is named - SpringBatchMain.java.
This will initialize context without starting any jobs.
3.Once context is initialized, either you can do - JobLauncher jobLauncher = (JobLauncher) ctx.getBean("jobLauncher");
or do Autowired
for this JobLauncher bean in main class and launch specific jobs sequentially in specific sequential order by invoking , jobLauncher.run(job, jobParameters)
.
You can get specific job
instances from context initialized at step # 2.
You can always use any ordered collection to put your jobs there and launch jobs by iterating over that collection.
4.This above technique works as long as your JobLauncher is configured to be synchronous i.e. main thread waits for jobLauncher.run()
call to complete and that is default behavior of jobLauncher.
If you have defined your jobLauncher to use AsyncTaskExecutor then jobs will be started in parallel and sequential ordering will not be maintained.
Hope it helps !!
EDIT:
I was experimenting with @Order
annotation as pointed by Stephane Nicoll and it seems to help only in creating an Ordered collection of jobs and that you can iterate and launch jobs in that order.
This below component gives me jobs in Order specified ,
@Component
public class MyJobs {
@Autowired
private List<Job> jobs;
public List<Job> getJobs() {
return jobs;
}
}
and I can do , MyJobs myJobs = (MyJobs) ctx.getBean("myJobs");
in main class provided bean is defined,
@Bean
public MyJobs myJobs() {
return new MyJobs();
}
I can iterate over myJobs
and launch jobs in that order as specified by @Order annotation.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…