Want to get total row count in footer of spring batch without customizing writer(Delegate Pattern)

时光怂恿深爱的人放手 提交于 2019-12-11 16:12:34

问题


This is my footer class:--

public class SummaryFooterCallback extends StepExecutionListenerSupport implements FlatFileFooterCallback{

    private StepExecution stepExecution;

    @Override
    public void writeFooter(Writer writer) throws IOException {
        writer.write("footer - number of items written: " + stepExecution.getWriteCount());
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }


}

This is my xml:--

<bean id="writer" class="org.springframework.batch.item.file.FlatFileItemWriter"> <property name="resource" ref="outputResource" /> <property name="lineAggregator"> <bean class="org.springframework.batch.item.file.transform.PassThroughLineAggregator" /> </property> <property name="headerCallback" ref="headerCopier" /> <property name="footerCallback" ref="footerCallback" /> </bean> <bean id="footerCallback" class="org.springframework.batch.sample.support.SummaryFooterCallback"/>

Failing at stepExecution.getWriteCount() with nullpointer Exception.

No, I haven't registered callback as a listener in the step. I am new to Java and Spring Batch, referring to your book Pro Spring Batch but not able to get the solution of the assigned task.


回答1:


You need to set the writer in scope step. Here you have a java based config that worked for me.

@Bean
@StepScope
public ItemStreamWriter<Entity> writer(FlatFileFooterCallback footerCallback) {
    FlatFileItemWriter<Entity> writer = new FlatFileItemWriter<Entity>();
    ...
    writer.setFooterCallback(footerCallback);
    ...
    return writer;
}

@Bean
@StepScope
private FlatFileFooterCallback getFooterCallback(@Value("#{stepExecution}") final StepExecution context) {
    return new FlatFileFooterCallback() {
        @Override
        public void writeFooter(Writer writer) throws IOException {
            writer.append("count: ").append(String.valueOf(context.getWriteCount()));
        }
    };
}


来源:https://stackoverflow.com/questions/45542978/want-to-get-total-row-count-in-footer-of-spring-batch-without-customizing-writer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!