Search code examples
javaspring-bootspring-batchchunks

Sharing object from LineCallbackHandler to ExecutionCOntext


I have a csv file with one line on the top considered as the header. My reader configuration is as following :

FlatFileItemReader<EncCreditEntrepIndDTO> reader = new FlatFileItemReaderBuilder<EncCreditEntrepIndDTO>()
            .strict(false)
            .resource(resource)
            .linesToSkip(1)
            .skippedLinesCallback(headerHandler)
            .lineMapper(mapper)
            .saveState(false)
            .build();
    return reader;

This is my LineCallbackHandler :

public class HeaderHandler implements LineCallbackHandler {


@Override
public void handleLine(String line) {
    AtomicReference<StepHeader> headerLine = new AtomicReference<>();
    processLine(line, headerLine);

}

After processing the headerline, i want to save it in the execution context to use it later in some steps . I tried implementing StepListener and then StepExecutionListener and retrieve the actual context. It is always equals to null


Solution

  • I tried implementing StepListener and then StepExecutionListener and retrieve the actual context. It is always equals to null

    Implementing StepExecutionListener should work if you register your callback handler as a listener in the step:

    @Bean
    public FlatFileItemReader<EncCreditEntrepIndDTO> itemReader(HeaderHandler headerHandler) {
        return new FlatFileItemReaderBuilder<EncCreditEntrepIndDTO>()
                // ...
                .skippedLinesCallback(headerHandler)
                .build();
    }
    
    @Bean
    public Step step(StepBuilderFactory stepBuilderFactory, HeaderHandler headerHandler) {
        return stepBuilderFactory.get("step")
                .<EncCreditEntrepIndDTO, EncCreditEntrepIndDTO>chunk(5)
                .reader(itemReader(headerHandler))
                .writer(itemWriter())
                .listener(headerHandler)
                .build();
    }