개발강의정리/Spring

[스프링 프레임워크 핵심 기술] 3-2. Vaildation 추상화

nineDeveloper 2019. 10. 6.
728x90

스프링 프레임워크 핵심 기술

포스팅 참조 정보

GitHub

공부한 내용은 GitHub에 공부용 Organizations에 정리 하고 있습니다

해당 포스팅에 대한 내용의 GitHub 주소

실습 내용이나 자세한 소스코드는 GitHub에 있습니다
포스팅 내용은 간략하게 추린 핵심 내용만 포스팅되어 있습니다

https://github.com/freespringlecture/spring-core-tech/tree/chap03-02-validation

 

freespringlecture/spring-core-tech

백기선님의 스프링 프레임워크 핵심 기술 강의 내용 정리. Contribute to freespringlecture/spring-core-tech development by creating an account on GitHub.

github.com

해당 포스팅 참고 인프런 강의

https://www.inflearn.com/course/spring-framework_core/dashboard

 

스프링 프레임워크 핵심 기술 - 인프런

이번 강좌는 스프링 부트를 사용하며 스프링 핵심 기술을 학습합니다 따라서 스프링 부트 기반의 프로젝트를 사용하고 있는 개발자 또는 학생에게 유용한 스프링 강좌입니다. 초급 웹 개발 Java Spring 온라인 강의

www.inflearn.com

실습 환경

  • Java Version: Java 11
  • SpringBoot Version: 2.1.2.RELEASE

3-2. Validation 추상화

org.springframework.validation.Validator

애플리케이션에서 사용하는 객체 검증용 인터페이스

특징

 

LocalValidatorFactoryBean (Spring Framework 5.2.0.RELEASE API)

This is the central class for javax.validation (JSR-303) setup in a Spring application context: It bootstraps a javax.validation.ValidationFactory and exposes it through the Spring Validator interface as well as through the JSR-303 Validator interface and

docs.spring.io

인터페이스

구현해야 되는 두가지 메서드

  • boolean supports(Class clazz): 어떤 타입의 객체를 검증할 때 사용할 것인지 결정함
  • void validate(Object obj, Errors e): 실제 검증 로직을 이 안에서 구현
    • 구현할 때 ValidationUtils 사용하며 편리 함.

스프링 부트 2.0.5 이상 버전을 사용할 때

  • LocalValidatorFactoryBean ​​빈으로 자동 등록
  • JSR-380(Bean Validation 2.0.1) 구현체로 hibernate-validator 사용.
  • https://beanvalidation.org/
    • 자바 표준 JEE 스펙
    • NotEmpty, NotNull, NotBlank, Email, Size ... 애노테이션들로 빈의 데이터를 검증할 수 있는 기능
 

Bean Validation - Home

Bean Validation is a Java specification which lets you express constraints on object models via annotations lets you write custom constraints in an extensible way provides the APIs to validate objects and object graphs provides the APIs to validate paramet

beanvalidation.org

에러코드

만든 에러코드 외에 다른 에러코드들을 Validatior가 추가 해줌

notempty.event.title
notempty.title
notempty.java.lang.String
notempty

애노테이션 검증

아래와 같이 간단하게 애노테이션 검증이 가능하며
복잡한 검증이 필요하다면 validate를 직접 구현하여 검증하면 됨

public class Event {
    Integer id;

    @NotEmpty
    String title;

    @NotNull @Min(0)
    Integer limit;

    @Email
    String email;
}
===== error code =====
Min.event.limit
Min.limit
Min.java.lang.Integer
Min
반드시 0보다 같거나 커야 합니다.
===== error code =====
NotEmpty.event.title
NotEmpty.title
NotEmpty.java.lang.String
NotEmpty
반드시 값이 존재하고 길이 혹은 크기가 0보다 커야 합니다.
===== error code =====
Email.event.email
Email.email
Email.java.lang.String
Email
이메일 주소가 유효하지 않습니다.
728x90

댓글

💲 추천 글