11
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring-Batch FlatFileItemWriterの使い方

Last updated at Posted at 2016-04-21

Spring-BatchにおけるFlatFileItemWriterの実装方法に関して、ググッても全く出てこなかったので仕方なくライブラリのソースを読みつつ実装したので以下に残す。

SampleAggregator.java
public class SampleAggregator implements LineAggregator<SampleInputDto>{

	@Override
	public String aggregate(SampleInputDto item) {
		StringBuilder sb = new StringBuilder();
		sb.append(item.getParam1());
		sb.append(",");
		sb.append(item.getParam2());
		sb.append(",");
		sb.append(item.getParam3());
		return sb.toString();
	}
}
SampleBatchConfiguration.java
    @Bean
    public FlatFileItemWriter<SampleOutputDto> writer() {
    	FlatFileItemWriter<SampleOutputDto> writer = new FlatFileItemWriter<SampleOutputDto>();
    	writer.setResource(new FileSystemResource("C:¥tenp¥sample-data.csv"));
    	writer.setLineAggregator(new SampleAggregator()); 
        return writer;
    }

はまったのは、以下の1点。

LineAggregatorインターフェースをimplementsして、aggregateメソッドを@OverrideしたクラスのインスタンスをsetLineAggregator()で設定しないと(確か)IllegalArgumentExceptionが発生する

@Overrideするaggreageteメソッドの実装内容は、引数に入力のPOJOが渡されるので、ファイルの1行出力内容をString型で返却してやれば良い。

■補足
Java8ならラムダ式が使えるので、いちいちSampleAggregatorクラスを実装するのが面倒くさい場合、以下のようにも書ける。

SampleBatchConfiguration.java
    @Bean
    public FlatFileItemWriter<SampleOutputDto> writer() {
    	FlatFileItemWriter<SampleOutputDto> writer = new FlatFileItemWriter<SampleOutputDto>();
    	writer.setResource(new FileSystemResource("C:¥tenp¥sample-data.csv"));
    	writer.setLineAggregator(item -> {
    	        StringBuilder sb = new StringBuilder();
            sb.append(item.getParam1());
            sb.append(",");
            sb.append(item.getParam2());
            sb.append(",");
            sb.append(item.getParam3());
            return sb.toString();
    	});
        return writer;
    }

以下参考
http://www.mybatis.org/spring/ja/batch.html

11
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?