一种ControllerAdvice失效的解决方案

在一个Controller中开启 @ExcetionHandler注解可以对该Controller中的方法进行异常处理(返回统一的格式)

使用@ControllerAdvice注解 ,开启全局异常
有时会出现失效的情况,即开启了全局异常,也不能显示出想要的格式

一般网上给出的资料都是说扫描不到@ControllerAdvice,
给出两种解决方案,
1.让Controller extends @ControllerAdvice注解的类
2.给注解的类添加@ComponentScan,或者给@SpringBootApplication注解的主程序添加@ComponentScan注解

通过试验发现并不能解决问题。

试验后发现把@ControllerAdvice改为@RestControllerAdvice就行了。

官网也没有特别提醒这个,以下是官网给出的示例:

// 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 {}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 夜莺2517阅读 127,800评论 1 9
  • 版本:ios 1.2.1 亮点: 1.app角标可以实时更新天气温度或选择空气质量,建议处女座就不要选了,不然老想...
    我就是沉沉阅读 11,842评论 1 6
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 12,728评论 28 53
  • 兔子虽然是枚小硕 但学校的硕士四人寝不够 就被分到了博士楼里 两人一间 在学校的最西边 靠山 兔子的室友身体不好 ...
    待业的兔子阅读 7,508评论 2 9