Controller Advice

Dev.Hammy·2024년 4월 6일
0

반응형 스택에서 이에 상응하는 내용 보기

@ExceptionHandler, @InitBinder@ModelAttribute 메서드는 해당 메서드가 선언된 @Controller 클래스 또는 클래스 계층 구조에만 적용됩니다. 대신 @ControllerAdvice 또는 @RestControllerAdvice 클래스에서 선언되면 모든 컨트롤러에 적용됩니다. 또한 5.3부터 @ControllerAdvice@ExceptionHandler 메서드를 사용하여 @Controller 또는 다른 핸들러의 예외를 처리할 수 있습니다.

@ControllerAdvice@Component로 메타 annotation을 달기 때문에 컴포넌트 스캐닝을 통해 Spring 빈으로 등록할 수 있습니다. @RestControllerAdvice@ControllerAdvice@ResponseBody로 메타 annotation이 달려 있으며 이는 @ExceptionHandler 메서드가 HTML 뷰가 아닌 응답 본문 메시지 변환을 통해 반환 값을 렌더링한다는 것을 의미합니다.

시작 시 RequestMappingHandlerMapping 및 ExceptionHandlerExceptionResolver는 컨트롤러 advice 빈을 감지하고 이를 런타임에 적용합니다. @ControllerAdvice의 전역 @ExceptionHandler 메서드는 @Controller의 로컬 메서드 다음에 적용됩니다. 대조적으로 전역 @ModelAttribute@InitBinder 메소드는 로컬 메소드보다 먼저 적용됩니다.

@ControllerAdvice annotation에는 적용되는 컨트롤러 및 핸들러 세트의 범위를 좁힐 수 있는 속성이 있습니다. 예를 들어:

// 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 {}

이전 예제의 선택기는 런타임 시 평가되며 광범위하게 사용될 경우 성능에 부정적인 영향을 미칠 수 있습니다. 자세한 내용은 @ControllerAdvice javadoc을 참조하세요.

0개의 댓글