コントローラーのアドバイス

@ExceptionHandler@InitBinder@ModelAttribute メソッドは、それらが宣言されている @Controller クラスまたはクラス階層にのみ適用されます。代わりに、それらが @ControllerAdvice または @RestControllerAdvice クラスで宣言されている場合、すべてのコントローラーに適用されます。さらに、5.3 以降、@ControllerAdvice の @ExceptionHandler メソッドを使用して、任意の @Controller またはその他のハンドラーからの例外を処理できます。

@ControllerAdvice は @Component でメタアノテーションが付けられているため、コンポーネントスキャンを通じて Spring Bean として登録できます。

@RestControllerAdvice は、@ControllerAdvice と @ResponseBody を組み合わせたショートカットアノテーションであり、実質的には、例外ハンドラーメソッドがレスポンスボディにレンダリングされる @ControllerAdvice です。

起動時に、RequestMappingHandlerMapping および ExceptionHandlerExceptionResolver はコントローラーアドバイス Bean を検出し、実行時に適用します。@ControllerAdvice からのグローバル @ExceptionHandler メソッドは、@Controller からのローカルメソッドの後に適用されます。対照的に、グローバル @ModelAttribute および @InitBinder メソッドは、ローカルメソッドの前に適用されます。

デフォルトでは、@ControllerAdvice と @RestControllerAdvice の両方が、@Controller と @RestController を含むすべてのコントローラーに適用されます。アノテーションの属性を使用して、適用対象となるコントローラーとハンドラーのセットを絞り込むことができます。例:

  • 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 を参照してください。