@Valid
Valid 어노테이션은 자바 표준 스펙입니다.
Controller 계층에서 dto의 유효성을 검사할 때 사용합니다.
@PostMapping
public ApiResult<CreateGroupResponse> createGroup(@CurrentUser User user,
@Valid @RequestBody CreateGroupRequest createGroupRequest) {
return ApiUtils.success(groupService.createGroup(user, createGroupRequest));
}
검증할 dto 앞에 사용함으로써 내부 로직을 수행하기 전에 dto를 검사합니다.
public class CreateGroupRequest {
@Size(min = 2, max = 20, message = "그룹명은 2~20 글자여야 합니다.")
private String groupName;
private Boolean isPublic;
}
dto에는 @Size, @NotEmpty 등을 사용하여 유효성 검사 설정을 할 수 있고, 메시지를 설정할 수 있습니다.
@RestControllerAdvice
public class GlobalExceptionHandler {
// COMMON
@ExceptionHandler(MethodArgumentNotValidException.class)
ResponseEntity<ErrorResponse> methodArgumentNotValidException(MethodArgumentNotValidException e) {
FieldError error = e.getBindingResult().getFieldErrors().get(0);
return getErrorResponseEntity(e,
ErrorCode.METHOD_ARGUMENT_NOT_VALID,
error.getDefaultMessage(),
error.getField());
}
dto의 유효성 검사가 실패하면 MethodArgumentValidException
이 발생합니다. 그래서 위처럼 @ExceptionHandler를 사용하여 공통 예외처리를 할 수 있습니다.
@Validated
Validated 어노테이션은 스프링에서 제공합니다.
Controller 계층 뿐만 아니라 다른 계층에서도 유효성 검증이 가능합니다.
클래스 레벨에 선언하여 사용합니다.
public class GroupController {
private final GroupService groupService;
@GetMapping
public ApiResult<List<SearchGroupListResponse>> getGroupUserList(@RequestHeader String groupName) {
return ApiUtils.success(groupService.searchGroup(new SearchGroupListRequest(groupName)));
}
request header 에 값을 유효성 검사하고 싶은 상황입니다. 다음과 같이 사용할 수 있습니다.
@Validated
public class GroupController {
private final GroupService groupService;
@GetMapping
public ApiResult<List<SearchGroupListResponse>> getGroupUserList(@RequestHeader @NotBlank String groupName) {
return ApiUtils.success(groupService.searchGroup(new SearchGroupListRequest(groupName)));
}
헤더에 값을 넣지 않고 요청 시, 다음처럼 ConstraintViolationException
이 발생합니다.
javax.validation.ConstraintViolationException: getGroupUserList.groupName: 공백일 수 없습니다
예외처리를 할 경우 위처럼 GlobalExceptionHandler
에서 ConstraintViolationException
를 예외처리 하면 됩니다.
'Spring' 카테고리의 다른 글
Save 메서드 동작 원리 (1) | 2023.11.28 |
---|---|
Valid 어노테이션 커스텀해서 사용하기 (0) | 2023.10.22 |
조회 쿼리 메서드 사용 시 불필요한 Join 이 사용되는 이유 (0) | 2023.09.14 |
엔티티 저장 시 Select 쿼리를 호출 하는 이유 (0) | 2023.09.14 |
Could not safely identify store assignment for repository candidate interface (0) | 2023.09.14 |