【问题标题】:How to get Job parameteres in to item processor using spring Batch annotation如何使用spring Batch批注将作业参数输入到itemprocessor
【发布时间】:2015-07-31 02:34:47
【问题描述】:

我正在使用 Spring MVC。从我的控制器中,我调用 jobLauncher 并在 jobLauncher 中传递作业参数,如下所示,我使用注释来启用配置,如下所示:

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
        // read, write ,process and invoke job
} 

JobParameters jobParameters = new JobParametersBuilder().addString("fileName", "xxxx.txt").toJobParameters();
stasrtjob = jobLauncher.run(job, jobParameters);                              

and here is my itemprocessor                                                         
public class DataItemProcessor implements ItemProcessor<InputData, OutPutData> {

  public OutPutData process(final InputData inputData) throws Exception {

        // i want to get job Parameters here ????

  }

}

【问题讨论】:

    标签: java spring spring-mvc spring-batch spring-batch-admin


    【解决方案1】:

    1) 在数据处理器上添加范围注释,即

    @Scope(value = "step") 
    

    2) 在您的数据处理器中创建一个类实例,并使用值注释注入作业参数值:

    @Value("#{jobParameters['fileName']}")
    private String fileName;
    

    您的最终数据处理器类将如下所示:

    @Scope(value = "step")
    public class DataItemProcessor implements ItemProcessor<InputData, OutPutData> {
    
    @Value("#{jobParameters['fileName']}")
    private String fileName;
    
      public OutPutData process(final InputData inputData) throws Exception {
    
            // i want to get job Parameters here ????
          System.out.println("Job parameter:"+fileName);
    
      }
    
      public void setFileName(String fileName) {
            this.fileName = fileName;
        }
    
    
    }
    

    如果你的数据处理器没有初始化为 bean,请在其上添加 @Component 注解:

    @Component("dataItemProcessor")
    @Scope(value = "step")
    public class DataItemProcessor implements ItemProcessor<InputData, OutPutData> {
    

    【讨论】:

    • 如果您的处理器是在 XML 中配置的,您应该在其中添加范围,例如:
    • 有没有办法将自定义类型列表设置为作业参数并在项目处理器中获取该列表?
    • 不应该是@StepScope而不是@Scope(value = "step")吗?
    【解决方案2】:

    避免使用 Spring 的 hacky 表达式语言 (SpEL) 的更好解决方案(在我看来)是使用 @BeforeStepStepExecution 上下文自动连接到您的处理器中。

    在您的处理器中,添加如下内容:

    @BeforeStep
    public void beforeStep(final StepExecution stepExecution) {
        JobParameters jobParameters = stepExecution.getJobParameters();
        // Do stuff with job parameters, e.g. set class-scoped variables, etc.
    }
    

    @BeforeStep 注释

    标记在执行Step 之前要调用的方法,它来了 在创建并保留 StepExecution 之后,但在第一个之前 项目被读取。

    【讨论】:

    • 赞成 - 这是批次 1.5.10 中非常干净的方法
    猜你喜欢
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2014-02-09
    • 2017-06-15
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2019-11-14
    相关资源
    最近更新 更多