Spring Batch는 대용량 데이터를 안정적으로 처리하기 위한 프레임워크입니다. 이 과정에서 작업의 시작/종료 시점 혹은 예외 발생 시점에 후처리나 로깅, 알림 등의 기능이 필요할 수 있습니다.
이러한 작업을 도와주는 것이 바로 Listener입니다.
Spring Batch의 리스너는 Job, Step, Chunk 또는 Item 처리 과정의 특정 시점에 개입할 수 있게 해주는 확장 포인트입니다. 일반적으로 다음과 같은 목적에 사용됩니다:

public interface JobExecutionListener {
void beforeJob(JobExecution jobExecution);
void afterJob(JobExecution jobExecution);
}
public interface StepExecutionListener {
void beforeStep(StepExecution stepExecution);
ExitStatus afterStep(StepExecution stepExecution);
}
public interface ChunkListener {
void beforeChunk(ChunkContext context);
void afterChunk(ChunkContext context);
void afterChunkError(ChunkContext context);
}
public interface ItemReadListener<T> {
void beforeRead();
void afterRead(T item);
void onReadError(Exception ex);
}
public interface ItemProcessListener<I, O> {
void beforeProcess(I item);
void afterProcess(I item, O result);
void onProcessError(I item, Exception e);
}
public interface ItemWriteListener<T> {
void beforeWrite(List<? extends T> items);
void afterWrite(List<? extends T> items);
void onWriteError(Exception e, List<? extends T> items);
}
방법 1: 인터페이스 기반 구현
@Component
public class LoggingJobListener implements JobExecutionListener {
@Override
public void beforeJob(JobExecution jobExecution) {
System.out.println(">>> Job 시작!");
}
@Override
public void afterJob(JobExecution jobExecution) {
System.out.println(">>> Job 종료: 상태 = " + jobExecution.getStatus());
}
}
Job 또는 Step에 등록:
@Bean
public Job myJob() {
return jobBuilderFactory.get("myJob")
.listener(loggingJobListener)
.start(myStep())
.build();
}
방법 2: 어노테이션 기반 구현 (@Before, @After 등)
Spring Batch는 @BeforeStep, @AfterStep, @BeforeJob, @AfterJob 등 어노테이션도 제공합니다.
@Component
public class AnnotationBasedStepListener {
@BeforeStep
public void beforeStep(StepExecution stepExecution) {
System.out.println(">> Step 시작 전 실행");
}
@AfterStep
public ExitStatus afterStep(StepExecution stepExecution) {
System.out.println(">> Step 종료 후 실행");
return stepExecution.getExitStatus();
}
}