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


问题内容

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

@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 ????

  }

}

问题答案:

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> {