목차
배경
@RequestMapping(path = "/users", method = POST)
public ResponseEntity createUser(@Valid @RequestBody RegisterParam registerParam) {
@Vaild라는 어노테이션이 생소했다. 이번에 소스에서 접하게 된 김에 정리하려고 한다. 이것이 꼭 필요한건지, 또는 얼마나 유용한건지 확인해보려고 한다.
javax.validation
구현체
javax.validation-api⊂jakarta.validation-api⊂org.hibernate.validator.
- Bean Validation API(java EE) -Original이고, Hibernate validator도 이걸 기반으로 한다.
- Hibernate Validator Engine
- Apache Commons Validator -이건 javaEE와는 독자적으로 구현되었다.
- Jakarta Bean Validation API(Java EE가 9부터는 이클립스재단으로 넘어가면서 Jakarta라는 이름이 붙여졌다. 따라서 Java EE의 Bean validation API와 큰 차이가 없다. )
JSR
Initial버전은 JSR 303(2009년승인)에 명세되어 있다.(java EE 6의 스펙의 일부였다.)
1.1버전은 JSR349에 정의되어 있다. (소스코드들이 공개되었다,Di가적용되었다.method 검증이 가능해졌다.)
2.0버전부터 JSR 380이 생겼다. 2.0부터는 SE를 타겟으로 한다.
JSR 303
Emmanuel Bernard(Red Hat)가 주도한 Spec이다.
Goal
Validating data is a common task that occurs throughout an application, from the presentation layer to the persistence layer. Often the same validation logic is implemented in each layer, proving to be time consuming and errorprone. To avoid duplication of these validations in each layer, developers often bundle validation logic directly into the domain model, cluttering domain classes with validation code that is, in fact, metadata about the class itself. This JSR defines a metadata model and API for JavaBean validation. The default metadata source is annotations, with the ability to override and extend the meta-data through the use of XML validation descriptors. The validation API developed by this JSR is not intended for use in any one tier or programming model. It is specifically not tied to either the web tier or the persistence tier, and is available for both server-side application programming, as well as rich client Swing application developers. This API is seen as a general extension to the JavaBeans object model, and as such is expected to be used as a core component in other specifications. Ease of use and flexibility have influenced the design of this specification
JSR 380 - Bean Validation 2.0(2017년승인) 1
java8의 기능을 포함시켰다.(Optional and LocalDate.)
Most used Constraint classes
클래스 이름으로 바로 추정이 가능하다.
결론
도메인로직에 검증로직을 넣기 보다는, Controller단에 검증로직을 처리하는 것이 더 좋을 때에는(즉 검증의 책임이 도메인에 있기보다는 presentation layer에 있다고 볼 수 있을 때에 말이다. ) java에서 지원하는 bean validation을 사용하는 것이 바람직하다.
참고사이트
@Valid 를 이용해 @RequestBody 객체 검증하기 (tistory.com)
Java Bean Validation Basics | Baeldung
[Spring] @Valid와 @Validated를 이용한 유효성 검증의 동작 원리 및 사용법 예시 - (1/2) - MangKyu's Diary (tistory.com)
- 2017년 9월 21일에 java se 9가 출시되었다. [본문으로]
'프로그래밍 언어(must-have skills) > JAVA' 카테고리의 다른 글
정규표현식 -java.util.regex.Pattern (0) | 2023.01.07 |
---|---|
if/else문과 swich문의 성능 비교 . (0) | 2022.05.31 |
log4j취약점 패치 (0) | 2021.12.13 |
[자바]Collections.emptyMap() vs new HashMap() (0) | 2021.10.01 |
Garbage Collection (0) | 2021.09.08 |