본문 바로가기
Batch

스프링배치 scope

by 이석준석이 2021. 4. 4.

스프링 배치에서는 

  • @JobScope
  • @StepScope 

를 이용해서 bean Scope를 생성할 수 있다.


@JobScope

  • 는 step 에 사용할 수 있으며

@StepScope

  • 는 reader / processor / writer 혹은 tasklet 에 사용할 수 있다.

Thread-safe

  • Step 에 사용된 @JobScope 는 Job이 실행되는 경우, Late Binding 되어 프록시형태로 새로운 빈이 등록된다.
  • reader / processor / writer / tasklet에 사용된 @StepScope 는 매번 Step 이 실행되는 경우, Late Binding 되어 프록시형태로 새로운 빈이 등록된다

간단한 코드를 통해 새로운 Step 이 빈으로 등록되는지 확인해보았다.

  • @PostConstruct : 빈이 등록된 이후 한번 호출됨.
@Slf4j
@Configuration
@RequiredArgsConstructor
public class SampleJobConfig {
 
    private final JobBuilderFactory jobBuilderFactory;
 
    private final Step sampleStep;
 
    public static final String JOB_NAME = "sampleJobConfig";
 
    @Bean
    public Job sampleJob() {
        return jobBuilderFactory.get(JOB_NAME)
                .incrementer(new RunIdIncrementer())
                .start(sampleStep)
                .build();
    }
 
    @Bean
    @JobScope
    public Step sampleStep() {
        return new Step() {
            @Override
            public String getName() {
                return "sampleStep";
            }
 
            @Override
            public boolean isAllowStartIfComplete() {
                return false;
            }
 
            @Override
            public int getStartLimit() {
                return 10;
            }
 
            @Override
            public void execute(StepExecution stepExecution)  {
 
            }
 
            @PostConstruct
            void postConstruct() {
                log.info("jobScope Test : {}", this);
            }
        };
    }
}
@SpringBootTest
@SpringBatchTest
class SampleJobConfigTest {
 
    @Autowired
    JobLauncherTestUtils jobLauncherTestUtils;
 
    @Autowired
    Job job;
 
    @Test
    void test() throws Exception {
        jobLauncherTestUtils.setJob(job);
        jobLauncherTestUtils.launchJob();
 
        jobLauncherTestUtils.setJob(job);
        jobLauncherTestUtils.launchJob();
    }
}

'Batch' 카테고리의 다른 글

간단한 Batch Domain 알아보기  (0) 2020.11.14