3
2

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でreaderの値に応じてwriterを動的に切り替える

Posted at

たとえば、readerが整数を読み込み、偶数・奇数で異なるwriterを呼び出す、という例を考える。

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ClassifierCompositeItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableBatchProcessing
public class App {
	@Bean
	public Job job(JobBuilderFactory jobs, StepBuilderFactory steps) {
		return jobs
				.get("job")
				.start(step1(steps))
				.build();
	}

	ItemWriter<Integer> evenWriter() {
		return items -> items.forEach(i -> System.out.println("偶数" + i));
	}

	ItemWriter<Integer> oddWriter() {
		return items -> items.forEach(i -> System.out.println("奇数" + i));
	}

	public Step step1(StepBuilderFactory stepBuilderFactory) {
		ItemReader<Integer> reader = new ListItemReader<Integer>(IntStream.range(0, 100).boxed().collect(Collectors.toList()));

		ClassifierCompositeItemWriter<Integer> compositeWriter = new ClassifierCompositeItemWriter<Integer>();
		compositeWriter.setClassifier(number -> {
			if (number % 2 == 0) {
				return evenWriter();
			}
			return oddWriter();
		});

		return stepBuilderFactory
				.get("step1")
				.<Integer, Integer>chunk(4)
				.reader(reader)
				.writer(compositeWriter)
				.build();
	}

	public static void main(String[] args) {
		new SpringApplicationBuilder(App.class).run(args);
	}
}

ClassifierCompositeItemWriterは自身がwriterで、指定されたルーティングパターンを基に呼び出すwriterを切り替える。

これを実行すると以下のようになる。

偶数0
偶数2
奇数1
奇数3
...

chunk(4)なので、4件ごとに偶数・奇数writerがそれぞれ1度ずつ呼び出されている。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?