控制器建议
通常,@ExceptionHandler,@InitBinder和@ModelAttribute方法 适用
在@Controller类(或类层次结构)。如果你
希望这些方法更全局地应用(跨控制器),你可以在
类@ControllerAdvice或@RestControllerAdvice.
@ControllerAdvice被注释为@Component,这意味着此类类可以是
通过 Component scanning 注册为 Spring bean。@RestControllerAdvice是带有注解的合成注解
同时@ControllerAdvice和@ResponseBody,这本质上意味着@ExceptionHandler方法通过消息转换呈现到响应体
(相对于视图分辨率或模板渲染)。
启动时,用于@RequestMapping和@ExceptionHandler方法检测带有@ControllerAdvice,然后应用其
方法。全球@ExceptionHandler方法(来自@ControllerAdvice) 是
在本地 Bean 的 Swift Controller 之后应用(从@Controller).相比之下,全球@ModelAttribute和@InitBinder方法先于 local 方法应用。
默认情况下,@ControllerAdvice方法适用于每个请求(即所有控制器),
但是,您可以通过使用
annotation 中,如下例所示:
-
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 {}
前面示例中的选择器在运行时进行评估,可能会产生负面影响
性能。请参阅@ControllerAdvicejavadoc 了解更多详情。