구현하기 바빠서 그냥 대충 훑고 넘어간 부분들을 조금이라도 정리해보고자 쓰는 TIL 시리즈입니다.
ResponseEntity는?
보통 프로젝트를 할 때, RestController의 엔드포인트에서는 보통 ResponseEntity 객체로 반환하는 경우가 많다.
이 ResponseEntity는 왜 쓰게 되었고, 어떤 기능이 있는지 이번 기회에 뜯어보게 되었다.
public class ResponseEntity<T> extends HttpEntity<T> {
private final HttpStatusCode status;
public ResponseEntity(HttpStatusCode status) {
this((Object)null, (MultiValueMap)null, status);
}
public ResponseEntity(@Nullable T body, HttpStatusCode status) {
this(body, (MultiValueMap)null, status);
}
...
}
다음과 같이 ResponseEntity는 HttpEntity라는 클래스를 상속받고 있다.
public class HttpEntity<T> {
public static final HttpEntity<?> EMPTY;
private final HttpHeaders headers;
@Nullable
private final T body;
...
}
HttpEntity는 HttpHeaders와 HttpBody를 포함하고 있는 제너릭 클래스이다. 따라서 이를 상속받은 ResponseEntity는 HttpStatusCode와 함께 HttpEntity가 가지고 있는 헤더 정보와 바디로 구성되어 있고, HTTP 응답을 보다 세밀하게 제어할 수 있는 기능을 제공한다.
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, int rawStatus) {
this(body, headers, HttpStatusCode.valueOf(rawStatus));
}
위의 코드는 ResponseEntity의 여러 생성자들 중 하나이다. ResponseEntity의 생성자를 통해 개발자는 응답 상태 코드, 헤더, 바디를 모두 명시적으로 설정할 수 있음을 알 수 있다. 이러한 특성은 RESTful API 개발 시 표준적인 응답 형태를 만들 수 있다.
사용 방식
직접 생성자 방식
return new ResponseEntity<>(response, HttpStatus.OK);
return new ResponseEntity<>(headers, HttpStatus.CREATED);
위와 같이 직접적으로 객체 생성을 명시하여 파라미터를 전달하는 사용 방식이 있다. 커스텀한 상태 코드가 있다면 이를 직접 지정해 줄 수 있다.
정적 메서드 방식
@GetMapping("/{marker_id}")
public ResponseEntity<SurfingShopInfoResponse> getSurfingMarkerInfo(@PathVariable("marker_id") Long markerId) {
var response = surfingShopService.getSurfingMarkerInfo(markerId);
return ResponseEntity.ok().body(response); // 정적 메서드 방식
}
빌더 패턴 비스무리한 구조로 위와 같이 사용할 수 있다. 이 경우에는 위와 같은 형태로 메서드 체이닝 방식으로의 사용이 가능해진다. 개인적으로는 가독성 면에서 좋기 때문에 자주 이용하는 방식이다.
@RestController에서
@RestController의 기본 동작 (자동 직렬화)
@RestController
public class SimpleController {
@GetMapping("/user")
public User getUser() {
return new User("김철수", 25); // 자동으로 JSON 변환
}
// 응답: {"name": "김철수", "age": 25}
// 상태코드: 200 OK (기본값)
// 헤더: Content-Type: application/json
}
이 경우에는 자동으로 JSON으로 직렬화를 해주지만 HTTP 상태 코드는 항상 200으로만 고정될 수 밖에 없고, 헤더도 제어가 불가능한 형태이다.
@RestController
public class DetailController {
@GetMapping("/{marker_id}")
public ResponseEntity<SurfingShopInfoResponse> getSurfingMarkerInfo(@PathVariable("marker_id") Long markerId) {
var response = surfingShopService.getSurfingMarkerInfo(markerId);
return ResponseEntity.ok().body(response);
}
}
그러나 ResponseEntity를 씀으로써 상태 코드를 명시적으로 골라서 설정할 수 있고, 헤더의 추가나 제어(CORS, 캐시) 등이 용이해진다는 장점이 있다. 뿐만 아니라 에러 처리를 해줄 경우에도 좀 더 정교한 방식으로 처리를 해줄 수 있다. 이를 통해 좀 더 자세하고 정확한 응답 정보를 클라이언트에게 반환해 줄 수 있다는 장점이 있다.
https://devlog-wjdrbs96.tistory.com/182
[Spring Boot] ResponseEntity란 무엇인가?
먼저 REST API가 무엇인지는 아래 블로그를 먼저 잘 읽어보자. https://meetup.toast.com/posts/92 REST API 제대로 알고 사용하기 : TOAST Meetup REST API 제대로 알고 사용하기 meetup.toast.com 1. ResponseEntity란? Spring Fra
devlog-wjdrbs96.tistory.com
'TIL' 카테고리의 다른 글
| [TIL] jakarta vs springframework Transactional (0) | 2025.10.02 |
|---|---|
| [TIL] Layered Architecture (0) | 2025.10.01 |
| [TIL] Java에서의 병렬 처리 (1) | 2025.09.26 |
| [TIL] 스케줄링 (@Scheduled & Quartz) (0) | 2025.09.24 |
| [TIL] Spring MVC - DispatcherServlet (0) | 2025.09.17 |