springspring-batchspring-batch-adminspring-batch-taskletspring-batch-stream

In Spring Batch, linked with a ItemReader call I want to call a static util method to populate a string


I have a Spring Batch reader with following configurations. This reader is reading from the database and and at a time its reading a page size records.

    @Autowired
    private SomeCreditRepot someCreditRepo;

    public RepositoryItemReader<SomeCreditModel> reader() {
         RepositoryItemReader<SomeCreditModel> reader = new RepositoryItemReader<>();
         reader.setRepository(someCreditRepo);
         reader.setMethodName("someCreditTransfer");
         .
         .
         
         ..
         return reader;
      }

I want to call utils method,

     refValue = BatchProcessingUtil.generateSomeRefValue();

before the processor step, so that all the records fetched by the reader will have the same value set by which is given by the above call.

So that all the entity fetched by the reader will get the same value, in the processor.

And then this refValue will be written to another table StoreRefValue(table).

What is the right way to do this in Spring Batch? Should I fire the query to write the refValue, to the table StoreRefValue in the processor?


Solution

  • You can let your processor implement the interface StepExecutionListener. You'll then have to implement the methods afterStep and beforeStep. The first should simply return null, and in beforeStep you can call the utility method and save its return value.

    Alternatively, you can use the annotation @BeforeStep. If you use the usual Java DSL, it's not required to explicitly add the processor as a listener to the step. Adding it as a processor should suffice.

    There are more details in the reference documentation: https://docs.spring.io/spring-batch/docs/current/reference/html/step.html#interceptingStepExecution