3.14、使用@ControllerAdvice和@RestControllerAdvice通知控制器
文章目录
这一部分示例见这个项目的 mvc 分支下的 MyControllerAdvice.java 和 MyController.java
注解@ControllerAdvice是一个组件注解(component annotation),它允许实现类通过类路径扫描被自动检测到。当使用 MVC 命名空间或者 MVC 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.
请原谅我拙劣的英语水平。谢谢!
@RestControllerAdvice is an alternative where @ExceptionHandler methods assume @ResponseBody semantics by default.
@ControllerAdvice和@RestControllerAdvice都可以指向控制器的一个子集:
// 指向所有带有注解@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 文档。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论