만약 어떤 컨트롤러 메서드에 @PostMapping을 통해 요청이 온다 하자.
이때, @ReuqestBody를 붙인 매개변수 객체에 데이터가 담기질 않는다.
이유는 바로 Cannot construct instance of ... (no Creators, like default constructor, exist)인 것이다.
이 때 해결 방법은 DTO를 만들어 주는 것!
@PostMapping(path = "/api/v1/customers/{customerId}")
@ResponseBody
public Customer findCustomer(
@PathVariable("customerId") UUID customerId, @RequestBody Customer customer) {
logger.info("Got customer save request {}", customer);
return customer;
}
public record CustomerDto(UUID customerId,
String name,
String email,
LocalDateTime lastLoginAt,
LocalDateTime createdAt) {
static CustomerDto of(Customer customer) {
return new CustomerDto(
customer.getCustomerId(),
customer.getName(),
customer.getEmail(),
customer.getLastLoginAt(),
customer.getCreatedAt());
}
}