Spring/Spring MVC

[Spring MVC] 4-3. Handler Methods: Controller Advice

noahkim_ 2023. 10. 17. 10:46

1. Controller Advice

항목 설명
사용 어노테이션
- @ControllerAdvice
- @RestControllerAdvice: @ControllerAdvice + @ResponseBody 조합
기본 적용 범위
메서드가 선언된 @Controller 클래스 내에서만 적용됨
동작 기반 구성 요소 RequestMappingHandlerMapping,
ExceptionHandlerExceptionResolver가 감지하여 적용
내부 구성 가능 메서드 @ExceptionHandler, @InitBinder, @ModelAttribute
- @ExceptionHandler 우선순위
로컬 메서드가 전역 메서드보다 우선 적용됨
- @InitBinder / @ModelAttribute 우선순위
전역 메서드가 로컬 메서드보다 우선 적용됨
적용 범위 제한 옵션
basePackages, assignableTypes, annotations 등으로 대상 컨트롤러 지정 가능

 

 

예제) 적용 범위 제한

더보기
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}

// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}

 

출처