此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
控制器建议
通常,@ExceptionHandler
,@InitBinder
和@ModelAttribute
方法 适用在@Controller
类(或类层次结构)来声明它们。如果你希望此类方法更全局(跨控制器)应用,您可以在类中用@ControllerAdvice
或@RestControllerAdvice
.
@ControllerAdvice
注释为@Component
,这意味着此类类可以通过组件扫描注册为 Spring bean。@RestControllerAdvice
是一个组合的注释,它带有注释与@ControllerAdvice
和@ResponseBody
,这本质上意味着@ExceptionHandler
方法通过消息转换呈现到响应正文(与视图解析或模板呈现相比)。
启动时,的基础设施类@RequestMapping
和@ExceptionHandler
方法检测带有@ControllerAdvice
然后在运行时应用它们的方法。 全球@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 了解更多详情。