본문 바로가기
Java & Kotlin/Spring Batch

[Spring Batch] @JobScope와 @StepScope

by heekng 2022. 5. 28.
반응형

@JobScope@StepScope

Scope란?

  • 스프링 컨테이너에서 빈이 관리되는 범위
  • singleton, prototype, request, session, application이 있으며 기본은 singleton으로 생성된다.

스프링 배치 스코프

@JobScope, @StepScope

@Bean
@JobScope
public Step step1(@Value("#{jobParameters['message']}") String message) {
    return stepBuilderFactory.get("step1")
            .tasklet(tasklet1(null))
            .build();
}

@Bean
@StepScope
public Tasklet tasklet1(
        @Value("#{jobExecutionContext['name']}") String name
) {
    return (contribution, chunkContext) -> {
        log.warn(">>tasklet1 has executed");
        return RepeatStatus.FINISHED;
    };
}

@Bean
@StepScope
public Tasklet tasklet2(
        @Value("#{stepExecutionContext['name2']}") String name2
) {
    return (contribution, chunkContext) -> {
        log.warn(">>tasklet2 has executed");
        return RepeatStatus.FINISHED;
    };
}
  • Job과 Step의 빈 생성과 실행에 관여하는 스코프
  • 프록시 모드를 기본값으로 하는 스코프: @Scope(value = "job", proxyMode = ScopedProxyMode.TARGET_CLASS)
  • @JobScope@StepScope가 선언되면 빈의 생성이 어플리케이션 구동시점이 아닌 빈의 실행시점에 이루어진다.
    • @Values를 주잉ㅂ해서 빈의 실행 시점에 값을 참조할 수 있으며 일종의 Lazy Binding이 가능해진다.
    • @Value(”#{jobParameters[파라미터명]}”), @Value(”#{jobExecutionContext[파라미터명]”}), @Value(”#{stepExecutionContext[파라미터명]”})
    • @Value를 사용할 경우 빈 선언문에 @JobScope, @StepScope를 정의하지 않으면 오류를 발생한다. 때문에 반드시 선언해야 한다.
  • 프록시 모드로 빈이 선어되기 때문에 어플리케이션 구동시점에는 빈의 프록시 객체가 생성되어 실행 시점에 실제 빈을 호출해준다.
  • 병렬처리 시 각 스레드마다 생성된 스코프 빈이 할당되기 때문에 스레드에 안전하게 실행이 가능하다.

@JobScope

@Bean
@JobScope
public Step step1(@Value("#{jobParameters['message']}") String message) {
    return stepBuilderFactory.get("step1")
            .tasklet(tasklet1(null))
            .build();
}
  • Step 선언문에 정의한다.
  • @Value: jobParameter, jobExecutionContext만 사용가능하다.

@StepScope

@Bean
@StepScope
public Tasklet tasklet1(
        @Value("#{jobExecutionContext['name']}") String name
) {
    return (contribution, chunkContext) -> {
        log.warn(">>tasklet1 has executed");
        return RepeatStatus.FINISHED;
    };
}

@Bean
@StepScope
public Tasklet tasklet2(
        @Value("#{stepExecutionContext['name2']}") String name2
) {
    return (contribution, chunkContext) -> {
        log.warn(">>tasklet2 has executed");
        return RepeatStatus.FINISHED;
    };
}
  • Tasklet이나 ItemReader, ItemWriter, ItemProcessor선언문에 정의한다.
  • @Value: jobParameter, jobExecutionContext, stepExecutionContext만 사용가능하다.
반응형