|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
控制器通知
通常,@ExceptionHandler、@InitBinder 和 @ModelAttribute 方法适用于声明它们的 @Controller 类(或类层次结构)中。如果您希望这些方法具有更全局的作用(跨控制器),您可以将它们声明在使用 @ControllerAdvice 或 @RestControllerAdvice 注解的类中。
@ControllerAdvice 被注解为 @Component,这意味着此类可以通过 组件扫描 注册为 Spring beans。@RestControllerAdvice 是一个组合注解,它被注解为 @ControllerAdvice 和 @ResponseBody,这基本上意味着 @ExceptionHandler 方法将通过消息转换渲染到响应体中(而不是视图解析或模板渲染)。
在启动时,@RequestMapping 和 @ExceptionHandler 基础架构类检测带有 @ControllerAdvice 注解的 Spring bean,并在运行时应用它们的方法。全局 @ExceptionHandler 方法(来自 @ControllerAdvice)在本地 @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])
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。