此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

控制器建议

通常,@ExceptionHandler,@InitBinder@ModelAttribute方法 适用 在@Controller类(或类层次结构)。如果你 希望这些方法更全局地应用(跨控制器),你可以在 类@ControllerAdvice@RestControllerAdvice.spring-doc.cadn.net.cn

@ControllerAdvice被注释为@Component,这意味着此类类可以是 通过 Component scanning 注册为 Spring bean。@RestControllerAdvice是带有注解的合成注解 同时@ControllerAdvice@ResponseBody,这本质上意味着@ExceptionHandler方法通过消息转换呈现到响应体 (相对于视图分辨率或模板渲染)。spring-doc.cadn.net.cn

启动时,用于@RequestMapping@ExceptionHandler方法检测带有@ControllerAdvice,然后应用其 方法。全球@ExceptionHandler方法(来自@ControllerAdvice) 是 在本地 Bean 的 Swift Controller 之后应用(从@Controller).相比之下,全球@ModelAttribute@InitBinder方法于 local 方法应用。spring-doc.cadn.net.cn

默认情况下,@ControllerAdvice方法适用于每个请求(即所有控制器), 但是,您可以通过使用 annotation 中,如下例所示:spring-doc.cadn.net.cn

// 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 了解更多详情。spring-doc.cadn.net.cn