728x90
@(Rest)ControllerAdvice 란
- 모든 @Controller 가 붙은 빈에서 사용하는 `@ExceptionHandler`, `@InitBinder`, `@ModelAttribute` 가 붙은 메소드들을 한번에 처리할 수 있도록 도와주는 기능
- 해당 컨트롤러 내에서 정의 시 해당 컨트롤러에서만 적용
- 전역적으로 사용하고 싶을 때 `@(Rest)ControllerAdvice` 를 활용
@ExceptionHandler
- `@Controller` 가 붙은 빈에서 발생한 예외를 잡아서 하나의 메서드에서 처리
@ControllerAdvice // 모든 컨트롤러에서 발생하는 exception 처리
public class GlobalHandler {
@ExceptionHandler(CustomException.class) // CustomException 이 발생할 경우 여기서 처리
public Object handleCustomException(HttpServletRequest request, CustomException e) {
log.error("handleCustomException", e);
if (CommonUtils.isAjaxRequest(request)) { // 해당 요청의 타입 구분 : ajax 인지 일반 request 요청인지
return returnResponseEntity(e); // ResponseEntity 타입으로 응답 리턴
} else {
return returnView(e); // ModelAndView 타입으로 응답 리턴
}
}
}
@InitBinder
- `@Controller` 가 붙은 빈에서 바인딩 또는 검증 설정을 변경하고 싶을 경우 사용
@RestControllerAdvice
public class ControllerAdvice {
@InitBinder("RaceResult")
public void initBind(final WebDataBinder webDataBinder) {
webDataBinder.setDisallowedFields("id");
}
}
@ModelAttribute
- `@Controller` 가 적용된 빈에서 웹 뷰로 넘겨주는 데이터 폼인 model 의 attribute 를 설정
- `@ModelAttribute` 는 메소드와 파라미터에 붙을 수 있음
- 모든 view 의 model 에서 특정 값을 공통적으로 사용하려고 할 경우 사용
@ControllerAdvice
public class ControllerAdvice {
@ModelAttribute
public void handleRequest(HttpServletRequest request, Model model) {
String requestURI = request.getRequestURI();
model.addAttribute("appVer", Const.AppVer);
model.addAttribute("uri", requestURI);
}
}
주의점
- `@(Rest)ControllerAdvice` 와 `@Controller` 에 모두 어노테이션이 적용된 경우
⇒ @Controller 에 적용된 어노테이션이 우선권을 가지게 됨
728x90
'Java | Spring' 카테고리의 다른 글
| [Spring] Interceptor 와 request.getInputStream() (1) | 2025.03.10 |
|---|---|
| [Spring] 예외 처리 - ExceptionResolver (0) | 2025.03.09 |
| [Spring] @RequestParam, @RequestBody, @ModelAttribute (1) | 2025.03.09 |
| [Java] 제네릭 (Generics) (2) | 2025.03.08 |
| [Java] 다형성과 캐스팅 (0) | 2025.03.08 |