Skip to content
Advertisement

Spring batch : ClassifierCompositeItemWriter footer not getting called

I am using Spring Batch to write multiple reports. Requirement is i will get records with BranchId and name. I need to create one file for each branchId and write respective data into that file along with some header and footer.

Example:

JavaScript

In this case it should create total 3 files

JavaScript

.

I am using ClassifierCompositeItemWriter to create / reuse the FlatFileItemWriter based on data(id in this case) & able to create the files successfully. For header and footer – using callbacks at writer level. Generated files are having only HEADER and DATA. But somehow FOOTER is not at all getting executed.

Looks like some issues with File closing before Footer or issue with usage of STEP SCOPE.

Can someone help me in getting the FOOTER called.

here is the code.

JavaScript

Advertisement

Answer

In my case, i don’t have fixed number writers (foo & boo in your case) and they will be dynamic and need to create at RUN time. Any suggestions on how to do it and register them to step?

In that case, you need to:

  1. pre-calculate the possible distinct values (1, 2 and 4 in your case) with a query like select distinct(id) from table for example or a similar mechanism depending on you input data
  2. dynamically create ItemWriter beans and register them as streams in your step.

The following is an example based on your use case: given a list of students in different groups, the idea is to write them in different files based on their group. Here is a tasklet that pre-calculates the distinct groups and creates/registers item writers dynamically in the application context:

JavaScript

Once that in place, a second step loads those item writers from the application context at runtime and registers them as delegates in a ClassifierCompositeItemWriter:

JavaScript

I have a complete example here: sample app for SO67604628. Please refer to this guide to see how to checkout a single folder (if you don’t want to clone the entire repo). The sample generates 3 files with students grouped by groupId. Note how headers/footers are correctly generated since delegate writers are registered as streams in the step.

Advertisement