728x90
300x250
@Controller 와 @RestController의 차이란?
1. @Controller
- 서버 사이드 렌더링(MVC)
- JSP, Thymeleaf 같은 View(html) 를 반환
@Controller
public class TestController {
@GetMapping("/test")
public String test(Model model) {
model.addAttribute("msg", "hello");
return "test"; // test.html or test.jsp
}
}
- 반환값 "test" --> 뷰 이름
- ViewResolver가 HTML 파일을 찾아서 렌더링
- Thymeleaf / JSP 사용, 서버에서 HTML 만들어서 내려줄 때 사용
데이터만 반환하고 싶으면 @ResponseBody를 메서드마다 붙여야한다.
2. @RestController
- REST API 전용
- JSON / XML 데이터 반환
@RestController
public class ApiController {
@GetMapping("/api/test")
public String test() {
return "hello";
}
}
- 반환값 "hello" --> JSON 응답
- HTTP Response Body로 바로 내려감
- React , Vue 등에서 사용하고 또한 요즘 대부분의 백엔드 API는 다 이걸로함
그냥 쉽게 한 줄로 요약하면 !!!
@RestController = @Controller + @ResponseBody
엥 그러면 @ControllerAdvice랑 @RestControllerAdvice는 뭐지?
3. @ControllerAdvice와 @RestControllerAdvice
~~Adivce 어노테이션은 여러 Controller에 공통으로 적용되는 로직을 한 곳에 모아두는 기능을 한다.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public String handleNPE(NullPointerException e) {
return "Null 포인터 에러 발생";
}
}
- 모든 @Controller, @RestController에 자동 적용
- 컨트롤러 코드에 중복되는 로직 제거
- 예외 처리 / 공통 데이터 바인딩 / 공통 설정에 많이 쓰인다.
역시나..
@RestControllerAdvice = @ControllerAdvice + @ResponseBody
API서버는 왠만하면 다 @RestControllerAdvice를 쓴다고 보면된다.
4. Controller에서 예외가 발생했을때 어떤 흐름으로 가나?
(1) Controller에서 예외 발생
(2) DispatcherServlet이 예외 캐치
(3) @ControllerAdvice의 @ExceptionHandler 검색
(4) 있으면 실행
(5) 응답 생성
참고로 @ControllerAdvice가 Controller 안의 try/catch보다 우선순위 높음
5. @RestControllerAdvice와 AOP의 차이
모든 컨트롤러에 공통으로 적용된다고 하니까 꼭 AOP와 비슷한 개념인거 같이 느껴졌다.
그치만 정확히는 AOP는 아니다.
아래 표를 보면 된다
AOP는 거의 로깅/트랜잭션에 포커싱이 되어있고
@ControllerAdvice는 예외처리 중심이다.
| @ControllerAdvice | AOP | |
| 적용 대상 | Controller 전용 | 모든 Bean |
| 주요 목적 | 예외 / MVC 공통 처리 | 로깅, 트랜잭션 등 |
| 동작 시점 | 요청 처리 중 | 메서드 호출 전/후 |
| 구현 방식 | Spring MVC 기능 | 프록시 기반 |
728x90
