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 文档

    原文作者:行一
    原文地址: https://segmentfault.com/a/1190000007013516
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞