此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
控制器建议
通常,@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 {}
前面示例中的选择器在运行时进行评估,可能会产生负面影响
性能。请参阅@ControllerAdvice
javadoc 了解更多详情。