spring/batch

#1. Job

tokkaiiii 2025. 4. 16. 09:40

1. Job 의 시작

 @Bean
  public Job job() {
    return new JobBuilder("step1", jobRepository)
        .start(step1())
        .next(step2())
        .build();
  }

start 가 실행되면 SimpleJobBuilder.class 에서 start 함수가 실행되고 steps list 에 step 을 넣는다.

 public SimpleJobBuilder start(Step step) {
    if (this.steps.isEmpty()) {
      this.steps.add(step);
    } else {
      this.steps.set(0, step);
    }

    return this;
  }

next 로 넘어가면 마찬가지로 SimpleJobBuilder.class 에 있는 next 함수를 실행하여 똑같이 steps list 에 step 을 넣는다.

 public SimpleJobBuilder next(Step step) {
    this.steps.add(step);
    return this;
  }

그러면 steps 는 두개의 step 을 가지고 build 를 한다. 

Job 객체가 만들어지는데 크게 FlowJob 과 SimpleJob 이 있다.

SimpleJobBuilder.class 의 build 함수를 보면 SimpleJob 을 만들고

step 을 다시 job 에 세팅한다

public Job build() {
    if (this.builder != null) {
      return ((FlowJobBuilder)this.builder.end()).build();
    } else {
      SimpleJob job = new SimpleJob(this.getName());
      super.enhance(job);
      job.setSteps(this.steps);

      try {
        job.afterPropertiesSet();
        return job;
      } catch (Exception e) {
        throw new JobBuilderException(e);
      }
    }
  }

SimpleJob 이 두개의 step 을 가진 컨테이너 역할을 한다.

step 은 스프링배치에서 하고자 하는 비즈니스로직을 담는다. 그런 내용을 포함하는 객체가 Job 그래서 Job 은 설계도 또는 명세서 역할을 한다.

 

설정이 마치면 BatchAutoConfiguration.class 에서 JobLauncher 를 가지고 실행하는 JobLauncherApplicationRunner 객체 생성

그러면 JobLauncherApplicationRunner.class 를 보면 jobLauncher 를 가지고 있다

JobExecution execution = this.jobLauncher.run(job, parameters);

jobLuncher 가 실행 주체다.

그러면 SimpleJob 이 실행되어야 한다.

 

TaskExecutorJobLauncher.class 를 보면 run 메소드 중 job.execute 에 디버그 걸어보면 job 에 SimpleJob 이 걸리는 걸 확인 할 수 있다.

					+ "]");
						}
						job.execute(jobExecution);
						if (logger.isInfoEnabled()) {
							Duration jobExecutionDuration = BatchMetrics.calculateDuration(jobExecution.getStartTime(),
									jobExecution.getEndTime());
							logger.info("

AbstractJob 으로 가서 doExecute 실행 그럼 AbsractJob 을 상속한 SimpleJob 클래스의 doExecute 가 실행된다.