控制器通知

@ExceptionHandler@InitBinder@ModelAttribute 方法僅應用於宣告它們所在的 @Controller 類或類層次結構。如果它們宣告在 @ControllerAdvice@RestControllerAdvice 類中,則應用於任何控制器。此外,從 5.3 版本開始,@ControllerAdvice 中的 @ExceptionHandler 方法可以用來處理來自任何 @Controller 或任何其他處理器的異常。

@ControllerAdvice 使用 @Component 進行了元註解,因此可以透過 元件掃描 註冊為 Spring Bean。@RestControllerAdvice 使用 @ControllerAdvice@ResponseBody 進行了元註解,這意味著 @ExceptionHandler 方法的返回值將透過響應體訊息轉換來渲染,而不是透過 HTML 檢視。

在啟動時,RequestMappingHandlerMappingExceptionHandlerExceptionResolver 會檢測控制器通知 Bean 並在執行時應用它們。來自 @ControllerAdvice 的全域性 @ExceptionHandler 方法在來自 @Controller 的區域性方法之後應用。相反,全域性 @ModelAttribute@InitBinder 方法在區域性方法之前應用。

@ControllerAdvice 註解具有一些屬性,允許你縮小其應用到的控制器和處理器的範圍。例如

  • Java

  • Kotlin

// 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 {}
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = [RestController::class])
class ExampleAdvice1

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

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = [ControllerInterface::class, AbstractController::class])
class ExampleAdvice3

前面示例中的選擇器在執行時進行評估,如果大量使用,可能會對效能產生負面影響。有關更多詳細資訊,請參閱 @ControllerAdvice 的 Javadoc。