이전 포스팅:
[Spring] Bean Validation (검증) - 1
[Spring] Bean Validation (검증) - 1
해당 예제는 다음과 같은 기술 스택을 사용했습니다.JDK 11Spring BootThymeLeaf 1. Bean Validation이란?Bean Validation은 Java EE 환경에서 표준으로 제공되는 유효성 검증 프레임워크로, JSR-380(Bean Validation 2.0)
eco-dev.tistory.com
Bean Validation의 한계와 해결책
문제점
- 등록과 수정 시 검증 조건이 다를 수 있음
- 하나의 도메인 객체에 모든 검증 로직을 담기 어려움
해결책
- 검증 그룹(groups) 사용: @Validated(SaveCheck.class)와 같이 그룹을 지정하여 상황별로 검증 조건을 다르게 적용
- 폼 객체 분리: 등록용 ItemSaveForm, 수정용 ItemUpdateForm과 같이 별도의 폼 객체를 만들어 사용
검증 그룹을 사용해도 되지만 더 복잡한 로직이 들어갈 시 관리에 어려움이 생길 수 있다.
따라서 2번 "폼 객체 분리" 를 사용해서 디벨롭을 해보겠다. 쉽게 설명하자면 컨트롤러에서 ModelAttribute로 바인딩하는 객체를 따로 생성 후 컨트롤러에서 도메인 객체로 변환하는 것이다.
Form 객체 분리하여 검증하기
폼 객체 생성
ItemSaveForm.java
public class ItemSaveForm {
@NotBlank
private String itemName;
@NotNull
@Range(min = 1000, max = 1000000)
private Integer price;
@NotNull
@Max(9999)
private Integer quantity;
// getters and setters
}
ItemUpdateForm.java
public class ItemUpdateForm {
@NotNull
private Long id;
@NotBlank
private String itemName;
@NotNull
@Range(min = 1000, max = 1000000)
private Integer price;
private Integer quantity;
// getters and setters
}
컨트롤러 수정
등록 컨트롤러
@PostMapping("/add")
public String addItem(@Validated @ModelAttribute("item") ItemSaveForm form, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return "validation/v4/addForm";
}
// 폼 객체를 도메인 객체로 변환 후 저장
}
수정 컨트롤러
@PostMapping("/{itemId}/edit")
public String edit(@PathVariable Long itemId, @Validated @ModelAttribute("item") ItemUpdateForm form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "validation/v4/editForm";
}
// 폼 객체를 도메인 객체로 변환 후 업데이트
}
장점
- 등록과 수정 시 필요한 검증 로직을 분리하여 관리할 수 있음
- 도메인 객체와 폼 객체를 분리하여 역할을 명확히 구분
HTTP 메시지 컨버터와 Bean Validation
API 개발 시 @RequestBody를 사용하여 JSON 데이터를 받아올 때에도 Bean Validation을 적용할 수 있다.
컨트롤러 예시
@RestController
@RequestMapping("/validation/api/items")
public class ValidationItemApiController {
@PostMapping("/add")
public Object addItem(@RequestBody @Validated ItemSaveForm form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return bindingResult.getAllErrors();
}
// 성공 로직
return form;
}
}
주의사항
- @ModelAttribute와 달리 @RequestBody는 객체 변환에 실패하면 컨트롤러가 호출되지 않고 예외가 발생
- 예외 처리를 통해 커스텀 에러 메시지를 반환할 수 있음
마무리
이번 글에서는 JDK 11, Spring Boot, 그리고 Thymeleaf를 사용하여 Bean Validation을 적용하는 방법을 상세히 알아보았다. Bean Validation을 통해 데이터의 무결성을 보장하고, 효율적인 검증 로직을 구현할 수 있다. 특히 폼 객체를 분리하여 관리함으로써 유지 보수성과 확장성을 높일 수 있다.
Reference
'Spring Framework' 카테고리의 다른 글
[Spring] API 예외 처리 (1) | 2024.11.15 |
---|---|
[Spring] 예외 처리와 오류 페이지 (0) | 2024.11.12 |
[Spring] Bean Validation (검증) - 1 (4) | 2024.10.31 |
[Spring] 스프링 메시지, 국제화 (1) | 2024.10.29 |
[Spring] Argument Resolver 란? (0) | 2024.10.24 |