DEV-STUDY/Spring

dto 역직렬화에는 기본생성자 + 자바 리플렉션 사용

HwangJerry 2023. 10. 13. 15:48

문제 상황

@Data
@Builder
@AllArgsConstructor
public class CommentLikeCreateRequestDto {
    private Long commentId;
}

위와 같이 설정한 채로 commentLike를 수행하는 api를 테스트하던 중 아래와 같은 에러메시지를 만날 수 있었다.

 

org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: 
Cannot construct instance of likelion.univ.like.commentlike.dto.CommentLikeCreateRequestDto (although at least one Creator exists): 
cannot deserialize from Object value (no delegate- or property-based Creator); 

nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot construct instance of likelion.univ.like.commentlike.dto.CommentLikeCreateRequestDto (although at least one Creator exists): 
cannot deserialize from Object value (no delegate- or property-based Creator)

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot construct instance of likelion.univ.like.commentlike.dto.CommentLikeCreateRequestDto (although at least one Creator exists): 
cannot deserialize from Object value (no delegate- or property-based Creator)

슥 봐도 역직렬화에서 문제가 발생하는 것을 이해할 수 있다.

 

문제 해결

스프링은 기본적으로 json과 객체 간의 연결을 위해 직렬화와 역직렬화를 지원해주는데, 이를 수행하는 과정에서 내부적으로 기본 생성자를 사용한다고 한다.

 

더하여, 역직렬화 과정에서는 자바 리플렉션을 활용하여 역직렬화를 수행하기 때문에 접근 제어를 PRIVATE까지 닫아도 된다.

 

따라서 아래와 같이 수정해 주었다.

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE) // edited
public class CommentLikeCreateRequestDto {
    private Long commentId;
}