如何使用spring Batch注释将Job参数输入到项目处理器中

Mar*_*are 5 java spring spring-mvc spring-batch spring-batch-admin

我正在使用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 ????

  }

}
Run Code Online (Sandbox Code Playgroud)

Ami*_*ati 18

1)在数据处理器上放置范围注释即

@Scope(value = "step") 
Run Code Online (Sandbox Code Playgroud)

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

@Value("#{jobParameters['fileName']}")
private String fileName;
Run Code Online (Sandbox Code Playgroud)

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

@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;
    }


}
Run Code Online (Sandbox Code Playgroud)

如果您的数据处理器未初始化为bean,请在其上放置@Component注释:

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

  • 不应该是`@StessScope`而不是`@Scope(value ="step")`? (3认同)

hee*_*eez 11

避免使用 Spring 的 hacky 表达式语言 (SpEL) 的一个更好的解决方案(在我看来)是StepExecution使用@BeforeStep.

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

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

@BeforeStep注解

标记要在 aStep执行之前调用的方法,该方法在 aStepExecution创建并持久化之后,但在读取第一个项目之前。