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

控制器建议

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

@ControllerAdvice注释为@Component,这意味着此类类可以通过组件扫描注册为 Spring bean。@RestControllerAdvice是一个组合的注释,它带有注释与@ControllerAdvice@ResponseBody,这本质上意味着@ExceptionHandler方法通过消息转换呈现到响应正文(与视图解析或模板呈现相比)。spring-doc.cadn.net.cn

启动时,的基础设施类@RequestMapping@ExceptionHandler方法检测带有@ControllerAdvice然后在运行时应用它们的方法。 全球@ExceptionHandler方法(从@ControllerAdvice是在本地之后应用(从@Controller). 相比之下,全球@ModelAttribute@InitBinder方法在本地方法之前应用。spring-doc.cadn.net.cn

默认情况下,@ControllerAdvice方法适用于每个请求(即所有控制器),但您可以通过使用注释上的属性将其缩小到控制器的子集,如以下示例所示: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