Add timestamp to filename in StaxEventItemWriter

Viewed 74

I have the following Spring Batch itemwriter that streams to a file, but wish to add a timestamp to the filename.
The following code works but is incorrect, because the timestamp is set at startup time rather than on every batch run.
What I like to achieve is that a new filename gets assigned on every job run, any idea how to do this?

@Component
public class EccAddSumoItemWriter extends SumoStaxEventItemWriter<AddSubscriptionXml> {

    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH-mm-ss.SSS");

    public EccAddSumoItemWriter(@Value("${sumo.output_folder}") String sumoSavePath) {
        setShouldDeleteIfEmpty(true);
        setRootIdentification("editionCodeChanged_add");
        setResourcePath(sumoSavePath + "/edition_code_changed_add-" + now().format(DATE_FORMATTER) + ".xml");
    }

}

setResourcePath merely refers to:

protected void setResourcePath(String resourceFilePath) {
    this.setResource(new FileSystemResource(resourceFilePath));
}

What is the advised way of doing this in Spring Batch?

2 Answers

Ditch your EccAddSumoItemWriter and write an @Bean method that creates a @StepScope or @JobScope SumoStaxEventItemWriter.

@StepScope
@Bean
public SumoStaxEventItemWriter writer(@Value("${sumo.output_folder}") String sumoSavePath) {
  SumoStaxEventItemWriter writer = new SumoStaxEventItemWriter();
  writer.setShouldDeleteIfEmpty(true);
  writer.setRootIdentification("editionCodeChanged_add");
  writer.setResourcePath(sumoSavePath + "/edition_code_changed_add-" + now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH-mm-ss.SSS")) + ".xml");
  return writer;
}

Now when building your step use this step scoped writer and each time you will get a fresh instance configured accordingly.

From the theory it seems that simply @StepScope should resolve the problem.
I will test this.

After test, worked perfectly:

enter image description here

Related