How to get Spring batch job ContextId in ItemProcessor or ItemWriter?

I need to save Job ExecutionId as one of the Entity fields. (I use JpaItemWriter) One of the topics explained in the StepExcecution article, I can get StepContext β†’ JobExecution. In this case, how to get StepExecution?

(I don’t need to transfer any data from one step to another, all I need is JobExecuionId)

Thanks for the help, Muner Ahmed

+6
source share
5 answers

I suggest you use a processor that updates your Entity with a value. If your processors directly implement ItemProcessor<T> , you will not automatically receive StepExecution . To get StepExecution , do 1 of the following: - implement StepExecutionListener and set it as a variable from the beforeStep method - create a method called [something](StepExecution execution) and annotate using @BeforeStep

after you entered StepExecution through the listener, you can get jobExecutionId and set it to your entity

 public class MyEntityProcessor implements ItemProcessor<MyEntity, MyEntity> { private long jobExecutionId; @BeforeStep public void beforeStep(StepExecution stepExecution) { jobExecutionId = stepExecution.getJobExecutionId(); } @Override public MyEntity process(MyEntity item) throws Exception { //set the values item.setJobExecutionId(jobExecutionId); //continue return item; } } 
+2
source

We can set the scope as a job using the @Scope ("job") Itemprocessor and can easily get a JobExecution using the @Value ("# {jobExecution}" expression, as shown below.

 @Service @Scope("job") public class XsltTransformer implements ItemProcessor<Record, Record> { @Value("#{jobExecution}") private JobExecution jobExecution; } 
+2
source

If you want to use @BeforeStep in MyEntityProcessor, you must declare it as a listener

 <batch:listeners> <batch:listener ref="myEntityProcessor" /> </batch:listeners> 
+1
source

Scope as a job using @Scope("job") of and get a JobExecution using @Value("#{jobExecution}")

+1
source

I had a similar problem when I wanted to get JobInstanceID. The following shows how I got StepExecution and then JobExecution returned. Hope this helps.

 public class FoobarItemProcessor implements ItemProcessor<Foobar, Foobar> { private JobExecution jobExecution; @BeforeStep public void beforeStep(StepExecution stepExecution) { jobExecution = stepExecution.getJobExecution(); } 
0
source

All Articles