java - 在使用 Spring Batch 和 Spring Boot 时,如何始终为每次运行启动一个新的作业实例?

标签 java spring spring-boot spring-batch

在使用 Spring Batch 和 Spring Boot 时,我们将得到一个 Fat jar,其中包含我所有的 Spring Batch 作业,我希望能够通过指定作业名称从命令行触发特定作业,问题是spring batch 检测到作业已完成,因此只会运行一次作业,使用 spring boot,我们可以使用 --spring.batch.job.names=jobToRun 指定名称,问题是如何我让它始终启动一个新实例,并且仍然能够使用此机制来传递要运行的作业名称。

我没有配置JobLauncher,所以我猜它使用的是默认的JobLauncherCommandLineRunner,我当前配置的是:

@SpringBootApplication
@EnableBatchProcessing
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

通过此配置,我可以从命令行运行该作业:

java -jar batch.jar --spring.batch.job.names=job1ToRun

如何使用类似的机制为每次运行启动一个新实例?我需要从命令行指定作业名称来选择要运行的作业。

最佳答案

来自spring-batch documentation

The CommandLineJobRunner

Because the script launching the job must kick off a Java Virtual Machine, there needs to be a class with a main method to act as the primary entry point. Spring Batch provides an implementation that serves just this purpose: CommandLineJobRunner. It's important to note that this is just one way to bootstrap your application, but there are many ways to launch a Java process, and this class should in no way be viewed as definitive. The CommandLineJobRunner performs four tasks:

  • Load the appropriate ApplicationContext
  • Parse command line arguments into JobParameters
  • Locate the appropriate job based on arguments
  • Use the JobLauncher provided in the application context to launch the job.

一个非常基本的示例,说明如何执行此操作:

 public static void main(String[] args) throws Exception {
    ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
    JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
    String jobName = args[0] // assuming args[0] is the jobName
    JobParameters jobParameters = createJobParameters(args)
    Job jobInstance = ctx.getBean(jobName, Job.class);          
    jobLauncher.run(jobInstance, jobParameters);                   
}

private static JobParameters createJobParameters(String[] args) {
    // TODO: Create & return the needed parameters 
}

关于java - 在使用 Spring Batch 和 Spring Boot 时,如何始终为每次运行启动一个新的作业实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57424259/

相关文章:

java - Postgresql 枚举在 springboot 1.5->2.0 迁移期间中断

java - 日历类: set to ten days from now

java - 为什么我使用G1GC时Scan RS花费很长时间

java - 分配 Image 对象会导致不绘制任何内容

java - 创建 servlet 上下文资源 [WEB-INF/applicationContext.xml] 中定义的名称为 "datasource"的 bean 时出错

java - 当我尝试运行我的代码时,我收到 "java.lang.Exception: java.lang.IllegalStateException"

java - Android - Java 服务器和 android 客户端

java - 在基于注释的 Spring Web 应用程序中将请求发送到 Controller 之前拦截请求

spring-boot - webflux Mono 响应为空

java - 为什么Spring在配置时并不总是使用批量插入/更新?