SpringBatch - Get Line Number on FieldSetMapper

眉间皱痕 提交于 2019-11-29 17:02:42

I realized that I can get the lineNumber value into MyObject by overriding the DefaultLineMapper with my own LineMapper in this way:

import org.springframework.batch.item.file.FlatFileParseException;
import org.springframework.batch.item.file.LineMapper;
import org.springframework.batch.item.file.transform.LineTokenizer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import my.model.MyObject;

public class MyLineMapper<T> implements LineMapper<MyObject>, InitializingBean {

    private LineTokenizer tokenizer;

    private ResourceFieldSetMapper fieldSetMapper;

    public MyObject mapLine(String line, int lineNumber) throws Exception {
        try{
            MyObject r = fieldSetMapper.mapFieldSet(tokenizer.tokenize(line));
            // this is the modification
            r.setLineNumber(lineNumber);
            return r;
        }
        catch(Exception ex){
            throw new FlatFileParseException("Parsing error at line: " + lineNumber + 
                    ", input=[" + line + "]", ex, line, lineNumber); 
        }
    }

    public void setLineTokenizer(LineTokenizer tokenizer) {
        this.tokenizer = tokenizer;
    }

    public void setFieldSetMapper(ResourceFieldSetMapper fieldSetMapper) {
        this.fieldSetMapper = fieldSetMapper;
    }

    public void afterPropertiesSet() {
        Assert.notNull(tokenizer, "The LineTokenizer must be set");
        Assert.notNull(fieldSetMapper, "The FieldSetMapper must be set");
    }

}

Thanks for your help! I hope this works for someone!

Blessings!

I think you can use spEL expression #{fileReader.currentItemCount}, but there is the SB interface ItemCountAware for this purpose.

Marker interface indicating that an item should have the item count set on it. Typically used within an AbstractItemCountingItemStreamItemReader.

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