这一部分示例见这个项目的 mvc 分支下的 MyControllerAdvice.java 和 MyController.javahtml
注解@ControllerAdvice
是一个组件注解(component annotation),它容许实现类经过类路径扫描被自动检测到。当使用 MVC 命名空间或者 MVC Java 配置时自动启用。java
带有@ControllerAdvice
注解的类能够包含带有@ExceptionHandler
、@InitBinder
和@ModelAttribute
注解的方法,and these methods will apply to @RequestMapping
methods across all controller hierarchies as opposed to the controller hierarchy within which they are declared.git
请原谅我拙劣的英语水平。谢谢!web
@RestControllerAdvice
is an alternative where @ExceptionHandler
methods assume @ResponseBody
semantics by default.spring
@ControllerAdvice
和@RestControllerAdvice
均可以指向控制器的一个子集:api
// 指向全部带有注解@RestController的控制器 @ControllerAdvice(annotations = RestController.class) public class AnnotationAdvice {} // 指向全部指定包中的控制器 @ControllerAdvice("org.example.controllers") public class BasePackageAdvice {} // 指向全部带有指定签名的控制器 @ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class}) public class AssignableTypesAdvice {}
更多详情见@ControllerAdvice 文档。mvc