美文网首页
一种ControllerAdvice失效的解决方案

一种ControllerAdvice失效的解决方案

作者: _gitignore | 来源:发表于2021-04-12 15:43 被阅读0次

    在一个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 {}
    

    相关文章

      网友评论

          本文标题:一种ControllerAdvice失效的解决方案

          本文链接:https://www.haomeiwen.com/subject/icfxlltx.html