How do I get Spring Batch Job ContextId in ItemProcessor or ItemWriter?

后端 未结 6 2216
说谎
说谎 2021-02-20 18:12

I need to store Job ExecutionId as one of the fields of Entity. (I am using JpaItemWriter) One of topic here explains from StepExcecution, I can get StepContext -> JobExecution.

6条回答
  •  星月不相逢
    2021-02-20 18:23

    I would suggest you use a processor that updates your Entity with value. If your processors directly implements ItemProcessor then you will not automatically get the StepExecution. To get the 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 with @BeforeStep

    once you've injected the StepExecution via a listener, you can then get the jobExecutionId and set it into your entity

    public class MyEntityProcessor implements ItemProcessor {
    
    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;
    }
    
    }
    

提交回复
热议问题