How to get job parameters to element processor using spring batch annotation

I am using spring MVC. From my controller, I call jobLauncher

and jobLauncher

pass in the job parameters as shown below, and I use annotations to enable the config as shown below:

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

  }

}

      

+4


source to share


2 answers


1) Put the scope annotation on your data processor i.e.

@Scope(value = "step") 

      

2) Make an instance of the class in your data processor and inject the value of the job parameter using the value annotation:

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

      



Your final data processor class will look like this:

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


}

      

If your data processor is not initialized as a bean, add the @Component annotation to it:

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

      

+14


source


The best solution (in my opinion) that avoids the use of Spring Hacker Expression Language (SpEL) is to automatically StepExecution

context StepExecution

into your processor using @BeforeStep

.

In your cpu add something like:

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

      



annotation @BeforeStep

Flags a pre-execution method Step

that occurs after creation and saving StepExecution

, but before the first element is read.

0


source







All Articles