본문 바로가기

Web/spring

[Spring framework Web MVC docs] 1.3.7 ControllerAdvice

728x90

틀린 해석이 있다면 알려주세요

 


 

@ControllerAdvice 는 @Controller 가 있는 모든 곳에 initbinder, exceptionhandler, modelattribute를 어떻게 작업할지 미리 선언해준다

공통분모 같은??

 

 

@Controller 안에 @ExceptionHandler, @InitBinder, @ModelAttribute 를 선언하면 해당 컨트롤러에서만 적용된다

 

@ControllerAdvice, @RestControllerAdvice 를 사용하면 모든 컨트롤러에 적용이된다.

 

as of 5.3, @ExceptionHandler methods in @ControllerAdvice can be used to handle exceptions from any @Controller or any other handler.

 

 

@ControllerAdvice 는 @Component 컴포넌트스캐닝을 통해 빈으로 등록할 수 있다.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-java-instantiating-container-scan

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

 

 

 

시작할 때부터 RequestMappingHandleMapping 과 ExceptionHandlerExceptionResolver 를 감지하여 런타임에 적용된다

ControllerAdvice의 전역 ExceptionHandler 메서드는 컨트롤러의 로컬 메서드 다음에 적용된다.

반대로 전역 ModelAttribute 및 InitBinder 메서드는 로컬 메서드보다 먼저 적용된다.

 

사용할 컨트롤러만 선언하여 범위를 조정할 수 있다

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

 

너무 광범위하게 사용하는 것은 좋지않다

 

https://docs.spring.io/spring-framework/docs/6.0.4/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

 

ControllerAdvice (Spring Framework 6.0.4 API)

Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes. Classes annotated with @ControllerAdvice can be declared explicitly as Spring beans or auto-d

docs.spring.io

 

 

728x90