개발 일지/Spring

[Spring MVC] @Rest + @Controller/@ControllerAdvice

미숫가루설탕많이 2023. 2. 16. 08:52
@Controller / @RestController

 

 Spring에서 컨트롤러를 지정해 주기 위한 애너테이션은 @Controller와 @RestController가 있다.

 

 @Controller는 클래스를 SpringMVC 컨트롤러로 표시하는 데 사용되며, 주로 사용자의 요청을 처리하고 난 후 정해진 뷰에 객체를 넘겨주는 역할을 한다.

 

 @Controller는 전통적인 Spring MVC 컨트롤러이며, @RestController는 RESTful 웹 서비스 컨트롤러이다.

 

 Spring은 @Controller에 @ResponseBody를 추가해서 @RestController를 도입했으며, 이 둘은 HTTP Response Body가 생성되는 방식에 차이가 있다.

 

 @Controller는 Model 객체를 만들어 데이터를 담아서 View를 반환하고 @RestController는 객체 데이터 반환을 목적으로 객체 데이터를 JSON이나 XML 형식으로 HTTP 응답에 담아서 전송한다.

 

 Spring MVC에서는 특정 클래스에 @RestController를 추가하면 해당 클래스가 REST API의 리소스를 처리하기 위한 API 엔드포인트로 동작함을 정의한다. 또한, @RestController가 추가된 클래스는 애플리케이션 로딩 시에 Spring Bean으로 등록해 준다.

 

 

 

 

@ControllerAdvice / @RestControllerAdvice

 

 특정 클래스에 @RestControllerAdvice 애너테이션을 추가하면 여러개의 Controller 클래스에서 @ExceptionHandler, @InitBinder, @ModelAttribute가 추가된 메서드를 공유해서 사용할 수 있다. 즉, 예외 처리를 공통화할 수 있다는 것이다.

 

 @RestController와 마찬가지로 @RestControllerAdvice는 @ControllerAdvice에 @ResponseBody의 기능을 추가한 것이다.

 

 따라서 @RestControllerAdvice 애너테이션을 이용하면 JSON 형식의 데이터를 Response Body로 전송하기 위해 ResponseEntity 데이터를 래핑할 필요가 없다.

'개발 일지 > Spring' 카테고리의 다른 글

[Spring MVC] 예외 처리  (0) 2023.02.19
[Spring MVC] @Valid / @Validated  (0) 2023.02.18
Spring Boot DB 오류(Failed to configure a DataSource)  (0) 2023.02.16
[Spring MVC] DTO  (0) 2023.02.15
[Spring MVC] DispatcherServlet  (0) 2023.02.15