-
전역 컨트롤러: @(Rest)ControllerAdviceSPRING/스프링 MVC 2021. 7. 13. 02:01
예외 처리, 바인딩 설정, 모델 객체를 모든 컨트롤러 전반에 걸쳐 적용하고 싶은 경우에 사용한다.
- @ExceptionHandler
- @InitBinder
- @ModelAttributes
적용할 범위를 지정할 수도 있다.
- 특정 애노테이션을 가지고 있는 컨트롤러에만 적용하기
- 특정 패키지 이하의 컨트롤러에만 적용하기
- 특정 클래스 타입에만 적용하기
@ControllerAdvice(assignableTypes = {SampleController2.class, EventApi.class}) // 2. @ControllerAdvice(SampleController2.class) // 3. @ControllerAdvice("com.springhm.demo") public class BaseController { @ExceptionHandler({EventException.class, RuntimeException.class}) public String eventErrorHandler(EventException exception, Model model) { model.addAttribute("message","event error"); return "error"; } // 특정 컨트롤러에서 바인딩 또는 검증 설정을 변경하고 싶을 때 사용 @InitBinder public void initEventBinder(WebDataBinder webDataBinder) { webDataBinder.setDisallowedFields("id"); // EventValidator 속성 추가 webDataBinder.addValidators(new EventValidator()); } //ModelAttribute 또다른 용번 // @Controller 또는 @ControllerAdvice를 사용한 클래에스 모델 정보를 초기화할 때 사용한다. @ModelAttribute() public void categories(Model model) { model.addAttribute("categories", List.of("study", "seminar","hobby","social")); } }
-이전에 공부하였었던 @InitBinder, @ModelAttribute, @ExceptionHandler 등을 @ControllerAdvice를 사용하면 별도의 클래스에서 관리할 수 있다.
-@ControllerAdvice(assignableTypes = {SampleController2.class, EventApi.class})에서 처럼 ControllerAdvice를 적용하고 싶은 클래스들을 지정할 수 있다.
범위를 지정하는 다른 방법들
특정 클래스에 지정하는 방법
- @ControllerAdvice(annotations = SampleController2.class)
특정 패키지 이하에 있는 컨트롤러들에 적용하는 방법
- @ControllerAdvice("com.springhm.demo")
'SPRING > 스프링 MVC' 카테고리의 다른 글
예외 처리 핸들러: @ExceptionHandler (0) 2021.07.13 DataBinder: @InitBinder (0) 2021.07.11 모델: @ModelAttribute 또 다른 사용법 (0) 2021.07.11 핸들러 메소드 16부 - @ResponseBody & ResponseEntity (0) 2021.07.10 핸들러 메소드 15부: @RequestBody & HttpEntity (0) 2021.07.10