[Spring Boot]RequestBody가 동작하는 구조

Hyuk4316·2023년 12월 24일
1

Java Spring

목록 보기
1/3
post-thumbnail

RequestBody란

@RequestBody를 이용해 매개변수를 설정하면 Http 요청이 들어오게 되면 HttpRequest의 body 부분을 domain 객체로 변환해 넣어주게 된고, 이 과정에서 역직렬화(Json -> Java Object)가 일어난다.
참고자료(Baeldung)

@RestController
class A {
	@PostMapping
	public ResponseEntity<Object> postM(@RequestBody Article article) {
		// JSON body가 Article 이라는 오브젝트로 변환됨
		// . . .
	}
}

ObjectMapper

우리는 방금 '역직렬화' 라는 단어를 봤다. 해당 기능은 어디서 실행하는 것일까?

해당 기능은 ObjectMapper에서 수행된다. 해당 클래스는 Object to JSON과 JSON to Object의 기능을 수행한다.


객체의 생성자

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class package.name.ClassName]] with root cause
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `package.name.ClassName` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

역직렬화 대상 클래스에 Constructor를 추가하자 이러한 오류가 생겼다. 기존에는 lombok의 @RequiredArgsConstructor를 이용하고 있었다.

구글링을 통해 Stackoverflow글을 찾았고, 이 글에서 empty constructor가 필요하다는 점을 알게되었다.

이후 원인을 찾아보았고 Stackoverflow에서 정답을 알 수 있었다. 그 원인은 기본적으로 no-argument constructor를 이용해 클래스를 생성하고 setter를 이용해 값을 넣기 때문이었다.

profile
한국공학대학교 소프트웨어전공 23학번

0개의 댓글

관련 채용 정보