프레임워크/Spring

[Spring] @ResponseBody와 ResponseEntity의 차이는 무엇일까?

멍토 2021. 4. 25.

우리는 요청받는 내용에 응답하기 위해 응답결과를 Body에 넣어서 보내게 된다.

Spring에서 Body에 데이터를 넣어 보낼때 이를 명시해줘야 하는데 사용방법은 아래와 같다.

@Controller
public class AccountController {

    @GetMapping("/accounts/{id}")
    @ResponseBody
    public Account handle(@PathVariable long id) {
        // ...
    }
}

그렇지만 앞에서 작성한 RestController와 Controller의 차이에서 설명했듯이 이러한 내용은 RestController를 이용하면 붙이지 않아도 된다.

@RestController
public class AccountController {

    @GetMapping("/accounts/{id}")
    public Account handle(@PathVariable long id) {
        // ...
    }
}

반환 방식은 여러가지 방식으로 가능하다.

텍스트로만 보낼 수도 있고, 객체로 보낼 수도 있다.

@GetMapping(path = "/message")
@ResponseBody
public String string() {
    return "message";
}

@GetMapping(path = "/users")
@ResponseBody
public User responseBodyForUser() {
    return new User("name", "email");
}

이러한 변환은 HttpMessageConverter가 도와준다.

이와 비슷하게 동작을 도와주는 친구가 있다.

그 친구는 ResponseEntity이다.

ResponseEntity는 ResponseBody에 추가적으로 상태코드를 직접 다룰때 사용이 가능하다.

ResponseEntity.ok().build();
ResponseEntity.badRequest().build();
ResponseEntity.created().build();
ResponseEntity.status(200).build();
ResponseEntity.ok(user);

위와 같이 다양한 형식으로 사용이 가능하다.

ResponseEntity를 사용하면 따로 @ResponseBody를 붙이지 않고 사용이 가능하다.

여기서 생긴 일화로는 에러를 핸들링할때 @ControllerAdvice를 이용하여 에러를 따로 처리하고 있었다.

Body에 데이터를 넣으니 당연히 ResponseBody를 붙이거나 @RestControllerAdvice를 이용했어야 했는데 ResponseEntity를 쓰고있어서 이러한 내용을 몰랐었다.

나중에 리뷰를 받으면서 RestController를 쓰고있는데 왜 RestControllerAdvice를 안쓰냐고 물어봐서 그때 알게 되었다.

출처 : https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-return-types

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-responsebody

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-responseentity

댓글

💲 광고입니다.