Search code examples
spring-batchwriter

Spring Batch ItemWriter : post processing when all records have been read and processed


I have a step in my job with an ItemReader/ItemProcessor/ItemWriter. In my ItemWriter, I need to increment a variable for each record in order to know which is the line number of my record in the file. For now, I'm using a static variable which works well for what I want to do, when I'm processing a single file. Problem is : I can restart my job (with different parameters), and when I'm processing another file without restarting my app before, my variable doesn't restart to the initial number while it's static, and I can have my counter set to "33" instead of 1...

I guess I could work around this problem using the stepContext instead of using a static variable, but I don't like this way. I'd prefer to have a method called when all records have been processed (something like the FlatFileItemWriter's footerCallback), so that I could reset my static variable. I'd just like to avoid the stepContext way, actually.

Is there a method like this for a "classic" ItemWriter (not the predefined one for flat files) ? Or another way to do this ?


Solution

  • As I only wanted to do some processing when the whole file has been read and processed, I figured out that I can use the StepExecutionListener with its method afterStep. I can reset my static variable (or do whatever I want) when the step is done, so that I can run my job multiple times without having issues with my static fields values.