1. Spring Batch 알아보기

이종찬·2025년 7월 9일
0
post-thumbnail

1. Spring Batch란?

Spring Batch는 엔터프라이즈급 배치 처리를 위한 포괄적인 프레임워크입니다. 대용량 데이터 처리, 트랜잭션 관리, 작업 처리 통계, 작업 재시작, 건너뛰기, 리소스 관리 등의 기능을 제공합니다.

Spring Batch의 핵심 컴포넌트

• Job: 배치 처리 과정을 하나의 단위로 만든 객체
• Step: Job의 배치처리를 정의하고 컨트롤하는 하나의 단위
• JobRepository: 배치 처리 정보를 담고 있는 메커니즘
• JobLauncher: Job을 구동시키는 역할

2. 초기화 및 실행 순서

Spring Framework 6과 함께 도입된 Spring Batch 5에서는 이전 버전과 초기화 과정이 크게 달라졌습니다. 특히 @EnableBatchProcessing 어노테이션의 역할과 자동 구성 방식에 중요한 변화가 있습니다.

이전 버전의 경우 @EnableBatchProcessing 사용 시 BatchAutoConfiguration, SimpleBatchConfiguration, BatchConfigurerConfiguration순서로 초기화가 진행되었지만 다음과 같이 변경되었습니다.

2-1. BatchAutoConfiguration

BatchAutoConfiguration은 Spring Boot에서 Spring Batch를 자동으로 구성하는 핵심 클래스입니다.

스프링 배치가 초기화될 때 자동으로 실행되며, Job을 수행하는 JobLauncherApplicationRunner 빈을 생성합니다.

Spring Batch 5에서는 이러한 기본적인 배치 인프라 구성 요소들을 DefaultBatchConfiguration 클래스나 @EnableBatchProcessing 어노테이션이 존재하지 않을 때만 BatchAutoConfiguration이 활성화됩니다.

즉, Spring Batch 5에서는 @EnableBatchProcessing 어노테이션 없이도 기본 배치 구성이 자동으로 활성화됩니다.

2-2. SimpleBatchConfiguration

SimpleBatchConfiguration은 Spring Batch의 기본 구성을 제공하는 추상 클래스입니다.

JobRepository jobRepository(): 배치 메타데이터 저장소
JobLauncher jobLauncher(): Job 실행기
JobExplorer jobExplorer(): 배치 실행 정보 조회
PlatformTransactionManager transactionManager(): 트랜잭션 관리자

이 클래스는 @EnableBatchProcessing 어노테이션이 사용될 때 활성화되며, 배치 처리에 필요한 기본 빈들을 구성합니다.

2-3. DefaultBatchConfiguration

Spring Batch 5에서 가장 큰 변화 중 하나는 BatchConfigurerConfiguration이 제거되고 DefaultBatchConfiguration이 도입된 것입니다.

Spring Batch 4 Config

@Configuration
@EnableBatchProcessing
public class BatchConfig implements BatchConfigurer {
    // 모든 메서드를 구현해야 함
    @Override
    public JobRepository getJobRepository() throws Exception { ... }
    
    @Override
    public PlatformTransactionManager getTransactionManager() throws Exception { ... }
    
    @Override
    public JobLauncher getJobLauncher() throws Exception { ... }
    
    @Override
    public JobExplorer getJobExplorer() throws Exception { ... }
}

Spring Batch 5 Config

@Configuration
public class MyBatchConfiguration extends DefaultBatchConfiguration {
    
    // 필요한 메서드만 오버라이드
    @Override
    protected DataSource getDataSource() {
        return customDataSource();
    }
    
    @Bean
    public Job myJob(JobRepository jobRepository) {
        return new JobBuilder("myJob", jobRepository)
            .start(myStep(jobRepository))
            .build();
    }
}

Spring Batch 5에서는 DefaultBatchConfiguration을 상속받아 필요한 부분만 커스터마이징할 수 있습니다.

2-4. @EnableBatchProcessing 어노테이션의 역할 변화

Spring Batch 4에서는 @EnableBatchProcessing 어노테이션을 통해서 스프링 배치의 스프링 부트 자동설정을 활성화할 수 있었습니다.

@EnableBatchProcessing
@SpringBootApplication
public class BatchApplication {
    public static void main(String[] args) {
        SpringApplication.run(BatchApplication.class, args);
    }
}

하지만 이제는 스프링 부트의 자동설정을 사용하기 위해서는 @EnableBatchProcessing 어노테이션을 삭제해야 합니다.

@EnableBatchProcessing 명시하는 방법 또는 DefaultBatchConfiguration을 상속하여 활성화되는 빈은 이제 스프링 부트의 자동설정을 밀어내고(back-off), 애플리케이션의 설정을 커스텀하는 용도로 사용됩니다.

주요 변경 사항

  1. 자동 설정 비활성화: @EnableBatchProcessing이나 DefaultBatchConfiguration을 사용하면 spring.batch.jdbc.initialize-schema 등의 기본 설정이 동작하지 않습니다.
  2. JobLauncherApplicationRunner 비활성화: 5.0부터는 @EnableBatchProcessing, DefaultBatchConfiguration을 설정하면 @ConditionalOnMissingBean에 의해 JobLauncherApplicationRunner가 실행되지 않습니다.
  3. 수동 Runner 구현 필요: 부트를 실행시킬 때 Job이 자동으로 실행되지 않으므로 Runner의 구현이 필요합니다.

예제

@RequiredArgsConstructor
@Configuration
public class HelloJobConfig {

    private final JobRepository jobRepository;
    private final PlatformTransactionManager transactionManager;

    @Bean
    public Job helloJob(Step helloStep1, Step helloStep2) {
        return new JobBuilder("helloJob", jobRepository)
                .incrementer(new RunIdIncrementer())
                .start(helloStep1)
                .next(helloStep2)
                .build();
    }

    @Bean
    public Step helloStep1(Tasklet helloTasklet1) {
        return new StepBuilder("helloStep1", jobRepository)
                .tasklet(helloTasklet1, transactionManager)
                .build();
    }

    @Bean
    public Step helloStep2(Tasklet helloTasklet2) {
        return new StepBuilder("helloStep2", jobRepository)
                .tasklet(helloTasklet2, transactionManager)
                .build();
    }

    @Bean
    public Tasklet helloTasklet1() {
        return (contribution, chunkContext) -> {
            System.out.println("Hello Step 1");
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Tasklet helloTasklet2() {
        return (contribution, chunkContext) -> {
            System.out.println("Hello Step 2");
            return RepeatStatus.FINISHED;
        };
    }
}

정리

  1. 자동 구성 우선: @EnableBatchProcessing 없이도 기본 구성 활성화
  2. 구성 방식 변경: BatchConfigurerDefaultBatchConfiguration
  3. 빌더 팩토리 제거:
    JobBuilderFactorynew JobBuilder(name, jobRepository) 직접 사용
    StepBuilderFactorynew StepBuilder(name, jobRepository) 직접 사용
    • 팩토리 의존성 주입 불필요, 더 직관적인 API 제공
  4. Java 17 필수: Spring Framework 6과 함께 Java 17이 최소 요구사항
profile
왜? 라는 질문이 사라질 때까지

0개의 댓글