[JAVA] Dynamically switch writer according to reader value with spring-batch

For example, consider an example where a reader reads an integer and calls different writers for even and odd numbers.

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("Even" + i));
	}

	ItemWriter<Integer> oddWriter() {
		return items -> items.forEach(i -> System.out.println("Odd" + 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 </ code> is itself a writer and switches the writer to call based on the specified routing pattern.

When this is executed, it becomes as follows.

Even 0
Even number 2
Odd 1
Odd 3
...

Since it is chunk (4) </ code>, even and odd writers are called once for every four cases.

Recommended Posts