Table of Contents
Spring Boot – Request DTO, Response DTO 정리
Request DTO 세팅을 커스터마이징하고 싶었는데 괜찮을 글이 보여 정리합니다.
Request DTO
변환과정
Json -> Request DTO
변환과정을 정리합니다.
@PostMapping("/search")
public ResponseEntity<?> search(@RequestBody SearchCompanyDto dto) {
return service.search(dto);
}
실제 변환은 @RequestBody
에 의해 실행됩니다.
RequestBody 를 따라가면,
인터페이스 HttpMessageConverter 에 의해 변환이 된다고 코멘트에 적혀 있습니다.
Json 매핑에는 MappingJackson2HttpMessageConverter 가 사용됩니다.
실제 매핑은 getter, setter, reflection 에 의해 이루어집니다.
Reflection API란?
구체적인 클래스 타입을 알지 못해도 그 클래스의 정보(메서드, 타입, 변수 등등)에 접근할 수 있게 해주는 자바 API다.
커스터마이징
JsonCreator
, JsonProperty
를 이용해 커스터마이징 할 수 있습니다.
@Getter
@Setter
@NoArgsConstructor
public class SearchCompanyDto {
private Long companyId;
@JsonCreator
@Builder
public SearchCompanyDto(@JsonProperty("companyId") Long companyId) {
this.companyId = companyId;
}
}
디폴트 값 설정은 아래와 같이 할 수 있습니다.
@Getter
@Setter
@NoArgsConstructor
public class BaseSearchDto {
private Integer pageNo = ConstValue.MIN_PAGE_NO;
private Integer pageSize = ConstValue.MAX_PAGE_SIZE;
}
NotNull 체크
@Valid
implementation 'org.springframework.boot:spring-boot-starter-validation'
@Valid
, @NotNull
을 이용해 Null 값을 체크할 수 있다.
@PostMapping("/create")
public ResponseEntity<?> create(@Valid @RequestBody UserDto dto) {
return service.create(dto);
}
@Getter
@Setter
@NoArgsConstructor
public class UserDto {
@NotNull
private Long companyId;
private Long userId;
}
Exception 커스터마이징 하기
위 오류의 로그를 확인하면 MethodArgumentNotValidException
이 발생하는 것을 볼 수 있습니다.
@RestControllerAdvice("kr.pe.skyer9.warehouse.account.web")
public class RestExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
String message = ResponseCode.ERROR_FIELD_REQUIRED.getTitle();
if ("companyId".equals(Objects.requireNonNull(e.getFieldError()).getField())) {
message = String.format("필수값(%s)이 누락되었습니다.", "업체 ID");
}
System.out.println(e.getFieldError().getField());
return ResponseEntity.ok(new ApiResponseMessage(ResponseCode.ERROR_FIELD_REQUIRED, message));
}
}
@PathVariable
@PathVariable
은 required = true
가 기본값이므로 별도로 Null 체크는 하지 않아도 됩니다.
Response DTO
Response DTO -> Json
변환과정을 정리합니다.
@PostMapping("/search")
public ResponseEntity<?> search(@RequestBody SearchCompanyDto dto) {
return service.search(dto);
}
실제 변환은 ResponseEntity
에 의해 실행됩니다.