Link to home
Create AccountLog in
Avatar of Prashant Vasha
Prashant VashaFlag for India

asked on

Spring Batch: Include count of records in File Header.

I am writing a standalone application using Spring Batch. The below is my batch job configuration:
<batch:job id="sampleBatchJob">
        <batch:step id="createFile">
                <batch:chunk reader="sampleReader" writer="sampleFileWriter" processor="sampleRecordProcessor" commit-interval="500"/>
            <batch:listener ref="sampleStepExecutionListener" />
            <batch:listener ref="executionContextPromotionListener" />
    <bean id="executionContextPromotionListener"
        <property name="keys" value="recordCount" />
    <bean id="outputResource" class="">
        <constructor-arg type="java.lang.String" value="sample.csv" />

    <bean id="sampleReader" class="test.SampleDataItemReader" scope="step"/>

    <bean id="sampleFileWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
        <property name="resource" ref="outputResource"/>
        <property name="shouldDeleteIfExists" value="true" />
        <property name="headerCallback" ref="sampleFileWriterCallback" />
        <property name="lineAggregator">
            <bean class="test.SampleCustomLineAggregator" >
                <property name="delimiter" value="," />

    <bean id="sampleFileWriterCallback" class="test.SampleFileHeaderWriterCallback"/>

    <bean id="sampleRecordProcessor" class="test.SampleRecordProcessor"/>

    <bean id="sampleStepExecutionListener" class="test.SampleStepExecutionListener"/>

Open in new window

I have to include the count of records in the File Header and for the same I have declared a property "recordCount" in executionContextPromotionListener. I am setting the value for the property in the ItemReader implementation using the ExecutionContext.

But before the ItemReader is invoked, the Header Callback for the ItemWriter is invoked and the writeHeader(Writer) is executed. Also, I do not have access to the ExecutionContext object when the writeHeader(Writer) is executed.

Any suggestions, how I can pass the value from the reader to the FileHeaderWriterCallBack implementation?
Avatar of Prashant Vasha
Prashant Vasha
Flag of India image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account