2

I've been using SpringBatch for a few months now.. I used to store execution-related variables(like page count, item count, current position of a batch and so on) into Beans. Then those beans are mounted onto ItemReader, ItemProcessor, ItemWriter by using setVar(), getVar()-setters and getters. Also those beans are shared among threads with manual synchronization.

But now I found out this could be a wrong way of doing batch jobs. Beans mounted to ItemReaders can't be persistent in JobRepository and therefore unable to record states for stopping and restarting of a Job. So I still need to go back and use StepExecution/JobExecution. Those examples I found online are all based on either XML config, or the worse SpEL autowired to a setter method..

I use purely Java Config..Is there a Java config or Java code-oriented way of accessing StepExecution? What's the best practice for accessing various sorts of ExecutionContext?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
wokmi
  • 71
  • 1
  • 2
  • 4
  • Maybe this answers your question: http://stackoverflow.com/questions/6078009/how-to-get-access-to-job-parameters-from-itemreader-in-spring-batch?rq=1 – Kees de Kooter Dec 11 '15 at 13:50

2 Answers2

7

To get access to the StepExecution and the JobExecution your ItemReader, ItemProcessor, or ItemWriter will have to implement the StepExecutionListener.

For instance:

public class MyCustomItemWriter implements ItemWriter<Object>, StepExecutionListener {

    private StepExecution stepExecution;

    @Override
    public void beforeStep(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return stepExecution.getExitStatus();
    }

    @Override
    public void write(List<? extends Object> list) throws Exception {
        if (null == list || list.isEmpty()) {
            throw new Exception("Cannot write null or empty list");
        }
        ExecutionContext stepExecContext = this.stepExecution.getExecutionContext()
        ExecutionContext jobExecContext = this.stepExecution.getJobExecution().getExecutionContext();
        // TODO: Write your code here
    }
}
KMD
  • 121
  • 2
  • 5
1

To get access to StepExecution, JobExecution, you can use methods with annotations from package org.springframework.batch.core.annotation or implementing iterfaces like JobExecutionListener, StepExecutionListener depending on your needs

leonz
  • 133
  • 1
  • 4