작성
·
164
0
코드 1.
@Getter
@Builder
public class ConnectionRequest {
@NotNull(message = INVALID_CONNECTION_CODE_PATTERN)
@Pattern(regexp = CONNECTION_CODE_PATTERN, message = INVALID_CONNECTION_CODE_PATTERN)
private String connectionCode;
@NotNull(message = INVALID_DATE_PATTERN)
@DateTimeFormat(iso = ISO.DATE)
@Past(message = INVALID_FIRST_DATE_RANGE)
private LocalDate firstDate;
public ConnectionServiceRequest toConnectionServiceRequest() {
return ConnectionServiceRequest.builder()
.connectionCode(connectionCode)
.firstDate(firstDate)
.build();
}
}
코드 2.
@Getter
@Builder
public class FirstDateRequest {
@NotNull(message = INVALID_DATE_PATTERN)
@DateTimeFormat(iso = ISO.DATE)
@Past(message = INVALID_FIRST_DATE_RANGE)
private LocalDate firstDate;
public FirstDateServiceRequest toFirstDateServiceRequest() {
return FirstDateServiceRequest.builder()
.firstDate(firstDate)
.build();
}
}
코드 1을 @RequestBody를 사용해 요청을 보냈을 때는 정상적으로 작동하지만,
코드 2를 @RequestBody를 사용해 요청을 보냈을 때는 '(no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)' 오류가 발생하게 됩니다.
조금 알아본 결과, JSON을 파싱하는 라이브러리 에서는 기본 생성자가 필요해서 코드 2에 기본 생성자가 없어서 발생한 오류인 것 같지만,
그러면 코드 1도 오류가 발생해야 하는 것 아닌가요?
답변 1
0
객체로 변환할 때 생성자가 없다는 오류입니다. 코드 1과 코드 2의 차이점은 firstDate와 관련된 필드가 있느냐 없느냐 인데, 이 부분이 원인일 수 있습니다. 코드 1에는 firstDate와 관련된 필드가 있으므로 Lombok의 @Builder
어노테이션으로 자동으로 생성자가 생성됩니다. 그러나 코드 2엔 firstDate와 관련된 필드가 없으므로 생성자가 생성되지 않습니다.
따라서 코드 2에서도 생성자를 명시적으로 정의해줘야 합니다. 아래와 같이 생성자를 추가해 주세요.
@Getter
@Builder
public class FirstDateRequest {
@NotNull(message = INVALID_DATE_PATTERN)
@DateTimeFormat(iso = ISO.DATE)
@Past(message = INVALID_FIRST_DATE_RANGE)
private LocalDate firstDate;
public FirstDateRequest(LocalDate firstDate) {
this.firstDate = firstDate;
}
public FirstDateServiceRequest toFirstDateServiceRequest() {
return FirstDateServiceRequest.builder()
.firstDate(firstDate)
.build();
}
}
이렇게 생성자를 추가해주면 코드 2에서도 객체를 생성할 수 있게 됩니다.