Controller Advice

通常,@ExceptionHandler@InitBinder@ModelAttribute 方法在其声明的 @Controller 类(或类层次结构)中应用。如果希望这些方法更全局地(跨控制器)应用,可以在用 @ControllerAdvice@RestControllerAdvice 注解的类中声明它们。

@ControllerAdvice@Component 注解,这意味着此类可以通过 组件扫描 注册为 Spring bean。@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。