본문 바로가기
spring/spring batch

[Spring Batch4] batch step에서 processor chaining하는 방법

by moonsiri 2022. 2. 4.
728x90
반응형

다음과 같은 batch step이 존재할 때, processor를 추가하기 위해선 어떻게 해야 할까요?

@Bean
public Job ioSampleJob() {
	return this.jobBuilderFactory.get("ioSampleJob")
				.start(step1())
				.build();
}

@Bean
public Step step1() {
	return this.stepBuilderFactory.get("step1")
				.<Foo, Bar>chunk(2)
				.reader(fooReader())
				.processor(fooProcessor())
				.writer(barWriter())
				.build();
}
public class Foo {}

public class Bar {
    public Bar(Foo foo) {}
}

public class Foobar {
    public Foobar(Bar bar) {}
}

public class FooProcessor implements ItemProcessor<Foo, Bar> {
    public Bar process(Foo foo) throws Exception {
        //Perform simple transformation, convert a Foo to a Bar
        return new Bar(foo);
    }
}

public class BarProcessor implements ItemProcessor<Bar, Foobar> {
    public Foobar process(Bar bar) throws Exception {
        return new Foobar(bar);
    }
}

public class BarWriter implements ItemWriter<Bar> {
    public void write(List<? extends Bar> bars) throws Exception {
        //write bars
    }
}

public class FoobarWriter implements ItemWriter<Foobar>{
    public void write(List<? extends Foobar> items) throws Exception {
        //write items
    }
}

 

단순하게 stepBuilderFactory에 processor 메서드 체이닝을 해보았는데, 제대로 작동하지 않았습니다.

@Bean
public Step step1() {
	return this.stepBuilderFactory.get("step1")
				.<Foo, Bar>chunk(2)
				.reader(fooReader())
				.processor(fooProcessor())
				.processor(barProcessor())
				.writer(barWriter())
				.build();
}

 

spring 공식 문서를 살펴보니, processor를 체이닝 하기위해서는 CompositeItemProcessor를 사용하여 다음과 같이 구성하면 됩니다.

@Bean
public Step step1() {
	return this.stepBuilderFactory.get("step1")
				.<Foo, Foobar>chunk(2)
				.reader(fooReader())
				.processor(compositeProcessor())
				.writer(foobarWriter())
				.build();
}

@Bean
public CompositeItemProcessor compositeProcessor() {
	List<ItemProcessor> delegates = new ArrayList<>(2);
	delegates.add(new FooProcessor());
	delegates.add(new BarProcessor());

	CompositeItemProcessor processor = new CompositeItemProcessor();

	processor.setDelegates(delegates);

	return processor;
}

//@Bean
//public ItemProcessor<Foo, FooBar> compositeProcessor() {
//	CompositeItemProcessor<Foo, FooBar> processor = new CompositeItemProcessor<>();
//	processor.setDelegates(Arrays.asList(new FooProcessor(), new BarProcessor()));
//	return processor;
//}

 

 

[Reference]

https://docs.spring.io/spring-batch/docs/current/reference/html/processor.html#chainingItemProcessors

https://stackoverflow.com/questions/64009522/spring-batch-how-to-chain-multiple-itemprocessors-with-diffrent-types

 

728x90
반응형

댓글