Controller Advice

@ExceptionHandler@InitBinder@ModelAttribute 方法僅適用於宣告它們的 @Controller 類別或類別階層。相反地,如果它們在 @ControllerAdvice@RestControllerAdvice 類別中宣告,則它們適用於任何控制器。此外,從 5.3 開始,@ControllerAdvice 中的 @ExceptionHandler 方法可用於處理來自任何 @Controller 或任何其他處理程序的例外。

@ControllerAdvice 使用 @Component 進行元註解,因此可以透過元件掃描註冊為 Spring bean。@RestControllerAdvice 使用 @ControllerAdvice@ResponseBody 進行元註解,這表示 @ExceptionHandler 方法將透過回應本文訊息轉換來呈現其傳回值,而不是透過 HTML 視圖。

在啟動時,RequestMappingHandlerMappingExceptionHandlerExceptionResolver 會偵測 controller advice 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 以取得更多詳細資訊。