[SpringBatch 실습] 11. JobParameters 검증 CustomValidator 만들기 (JobParametersValidator 구현), 스프링 배치가 제공해주는 DefaultJobParametersValidator 사용해보기

반응형
728x90
반응형

Validator 생성

CustomJobParametersValidator.java

import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.JobParametersValidator;

public class CustomJobParametersValidator implements JobParametersValidator {
    @Override
    public void validate(JobParameters jobParameters) throws JobParametersInvalidException {
        // value 가 null 일때
        if (jobParameters.getString("name") == null) {
            throw new JobParametersInvalidException("name parameters is not found ");
        }
    }
}

1) name의 필수값 체크

if (jobParameters.getString("name") == null) {
    throw new JobParametersInvalidException("name parameters is not found ");
}

 

 

Job 생성

ValidatorConfiguration.java

import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.DefaultJobParametersValidator;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*
--job.name=validatorJob
 */

@Configuration
@RequiredArgsConstructor
public class ValidatorConfiguration {

    // job 생성
    private final JobBuilderFactory jobBuilderFactory;
    private final StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job validatorJob() {
        return this.jobBuilderFactory.get("validatorJob")
                /* step start */
                .start(validatorStep1())
                .next(validatorStep2())
                .validator(new CustomJobParametersValidator())
                .build();
    }

    @Bean
    public Step validatorStep1() {
        return stepBuilderFactory.get("validatorStep1")
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                        System.out.println("validatorStep1");
                        return RepeatStatus.FINISHED;
                    }
                })
                .build();
    }

    @Bean
    public Step validatorStep2() {
        return stepBuilderFactory.get("validatorStep2")
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                        System.out.println("validatorStep2");
                        return RepeatStatus.FINISHED;
                    }
                })
                .build();
    }
}

 

1) validator 설정

.validator(new CustomJobParametersValidator())

 

 

name 파라미터를 넣지 않고 실행한 경우

if (jobParameters.getString("name") == null) {
    throw new JobParametersInvalidException("name parameters is not found ");
}

우리가 던진 예외가 발생한다.

Caused by: org.springframework.batch.core.JobParametersInvalidException: name parameters is not found 
at com.project.springbatch._18_validator.CustomJobParametersValidator.validate(CustomJobParametersValidator.java:37) ~[main/:na]

validator()에서 오류가 발생하여, 어떤 Step도 실행되지 않았다.

그래서 BATCH_JOB_EXECUTION 테이블에도 데이터가 쌓이지 않는다.

 

 

name 파라미터를 넣고 실행한 경우

성공적으로 Job이 실행 완료되었다.

validatorStep1
validatorStep2

 

 

 

DB 테이블 조회

1) BATCH_JOB_EXECUTION

COLUMN VALUE
STATUS COMPLETED
EXIT_CODE COMPLETED
JOB_EXECUTION_ID 2

 

2) BATCH_JOB_INSTANCE

COLUMN VALUE
JOB_NAME validatorJob

 

3) BATCH_STEP_EXECUTION

  • validatorStep1
COLUMN VALUE
STEP_NAME validatorStep1
EXIT_CODE COMPLETED
STATUS COMPLETED
JOB_EXECUTION_ID 2

 

  • validatorStep2
COLUMN VALUE
STEP_NAME validatorStep2
EXIT_CODE COMPLETED
STATUS COMPLETED
JOB_EXECUTION_ID 2

 

4) BATCH_JOB_EXECUTION_PARAMS

COLUMN VALUE
TYPE_CD STRING
KEY_NAME name
STRING_VAL seohae
JOB_EXECUTION_ID 2

 

 

 

 

DefaultjobParametrsValidator 사용

스프링 배치가 제공하는 validator도 설정할 수 있다.

@Bean
public Job validatorJob() {
    return this.jobBuilderFactory.get("validatorJob")
            /* step start */
            .start(validatorStep1())
            .next(validatorStep2())
            //.validator(new CustomJobParametersValidator())
            .validator(
                    // 1번째 인자 : requiredKeys
                    // 2번째 인자 : optionalKeys
                    new DefaultJobParametersValidator(new String[]{"name", "date"}, new String[]{"count"}))
            .build();
}

1) 1번째 인자 : 필수 파라미터, 2번째 인자 : 옵션 파라미터

new DefaultJobParametersValidator(new String[]{"name", "date"}, new String[]{"count"}))

따라서 name, date 파라미터는 필수이고, count 는 필수가 아니다.

 

 

반응형

Designed by JB FACTORY