ItemStream은 Spring Batch에서 배치 작업의 중간 상태를 저장하거나 복원할 수 있도록 해주는 인터페이스입니다.
public interface ItemStream {
void open(ExecutionContext executionContext) throws ItemStreamException;
void update(ExecutionContext executionContext) throws ItemStreamException;
void close() throws ItemStreamException;
}
주요 메서드
Spring Batch는 실패한 Step을 재시작(restart)할 수 있는 기능을 제공합니다. 이때 처리 위치나 커서 정보 등을 저장하고 복원하기 위해 ItemStream이 필요합니다.
예를 들어 FlatFileItemReader는 파일을 읽는 위치 정보를 저장해두기 때문에, 실패 시 중간부터 다시 읽을 수 있습니다. 이는 내부적으로 ItemStream을 구현하여 가능한 것입니다.
배치 설정에서 @Bean 메서드에 @StepScope를 붙이면, 해당 Bean은 Step 실행 시점에 동적으로 생성됩니다. 이 기능은 StepExecutionContext에 접근하거나, Step 파라미터를 주입받는 데 유용합니다.
@Bean
@StepScope
public FlatFileItemReader<MyDto> reader(@Value("#{jobParameters['inputFile']}") String inputFile) {
FlatFileItemReader<MyDto> reader = new FlatFileItemReader<>();
reader.setResource(new FileSystemResource(inputFile));
// 기타 설정...
return reader;
}
하지만 이 때 반환 타입이 ItemReader 인터페이스로 한정되어 있다면, 내부적으로 ItemStream 기능이 누락될 수 있습니다.
❗ 문제 상황 예시
@Bean
@StepScope
public ItemReader<MyDto> reader() {
FlatFileItemReader<MyDto> reader = new FlatFileItemReader<>();
// 설정 생략
return reader;
}
위 코드에서는 반환 타입이 ItemReader이기 때문에, Spring Batch는 해당 Bean이 ItemStream을 구현하고 있다는 사실을 인식하지 못하고 Step에 등록하지 않습니다. 그 결과, 재시작 기능이 동작하지 않거나, 상태 저장이 되지 않는 문제가 발생할 수 있습니다.
✅ 해결 방법
반환 타입을 ItemStreamReader 또는 구체적인 구현체(FlatFileItemReader)로 명시해 주는 것이 안전합니다.
@Bean
@StepScope
public FlatFileItemReader<MyDto> reader() {
FlatFileItemReader<MyDto> reader = new FlatFileItemReader<>();
// 설정 생략
return reader;
}
이렇게 하면 Spring Batch가 ItemStream 인터페이스를 인식하여, 상태 관리가 정상적으로 작동하게 됩니다.