@ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强。让我们先看看@ControllerAdvice的实现:

  1.  
    package org.springframework.web.bind.annotation;
  2.  
     
  3.  
    @Target(ElementType.TYPE)
  4.  
    @Retention(RetentionPolicy.RUNTIME)
  5.  
    @Documented
  6.  
    @Component
  7.  
    public @interface ControllerAdvice {
  8.  
     
  9.  
    @AliasFor("basePackages")
  10.  
    String[] value() default {};
  11.  
     
  12.  
    @AliasFor("value")
  13.  
    String[] basePackages() default {};
  14.  
     
  15.  
    Class<?>[] basePackageClasses() default {};
  16.  
     
  17.  
    Class<?>[] assignableTypes() default {};
  18.  
     
  19.  
    Class<? extends Annotation>[] annotations() default {};
  20.  
    }

没什么特别之处,该注解使用@Component注解,这样的话当我们使用<context:component-scan>扫描时也能扫描到。

再一起看看官方提供的comment。

大致意思是:

  • @ControllerAdvice是一个@Component,用于定义@ExceptionHandler@InitBinder@ModelAttribute方法,适用于所有使用@RequestMapping方法。

  • Spring4之前,@ControllerAdvice在同一调度的Servlet中协助所有控制器。Spring4已经改变:@ControllerAdvice支持配置控制器的子集,而默认的行为仍然可以利用。

  • 在Spring4中, @ControllerAdvice通过annotations()basePackageClasses()basePackages()方法定制用于选择控制器子集。

不过据经验之谈,只有配合@ExceptionHandler最有用,其它两个不常用。

在SpringMVC重要注解(一)@ExceptionHandler@ResponseStatus我们提到,如果单使用@ExceptionHandler,只能在当前Controller中处理异常。但当配合@ControllerAdvice一起使用的时候,就可以摆脱那个限制了。

  1.  
    package com.somnus.advice;
  2.  
     
  3.  
    import org.springframework.web.bind.annotation.ControllerAdvice;
  4.  
    import org.springframework.web.bind.annotation.ExceptionHandler;
  5.  
    import org.springframework.web.bind.annotation.ResponseBody;
  6.  
     
  7.  
    @ControllerAdvice
  8.  
    public class ExceptionAdvice {
  9.  
     
  10.  
    @ExceptionHandler({ ArrayIndexOutOfBoundsException.class })
  11.  
    @ResponseBody
  12.  
    public String handleArrayIndexOutOfBoundsException(Exception e) {
  13.  
    e.printStackTrace();
  14.  
    return "testArrayIndexOutOfBoundsException";
  1.  
    @Controller
  2.  
    @RequestMapping(value = "exception")
  3.  
    public class ExceptionHandlerController {
  4.  
     
  5.  
    @RequestMapping(value = "e2/{id}", method = { RequestMethod.GET })
  6.  
    @ResponseBody
  7.  
    public String testExceptionHandle2(@PathVariable(value = "id") Integer id) {
  8.  
    List<String> list = Arrays.asList(new String[]{"a","b","c","d"});
  9.  
    return list.get(id-1);
  10.  
    }
  11.  
     
  12.  
    }

当我们访问http://localhost:8080/SpringMVC/exception/e2/5的时候会抛出ArrayIndexOutOfBoundsException异常,这时候定义在@ControllerAdvice中的@ExceptionHandler就开始发挥作用了。

如果我们想定义一个处理全局的异常

  1.  
     
  2.  
    package com.somnus.advice;
  3.  
     
  4.  
    import javax.servlet.http.HttpServletRequest;
  5.  
     
  6.  
    import org.springframework.core.annotation.AnnotationUtils;
  7.  
    import org.springframework.web.bind.annotation.ControllerAdvice;
  8.  
    import org.springframework.web.bind.annotation.ExceptionHandler;
  9.  
    import org.springframework.web.bind.annotation.ResponseBody;
  10.  
    import org.springframework.web.bind.annotation.ResponseStatus;
  11.  
     
  12.  
    @ControllerAdvice
  13.  
    public class ExceptionAdvice {
  14.  
     
  15.  
    @ExceptionHandler({ Exception.class })
  16.  
    @ResponseBody
  17.  
    public String handException(HttpServletRequest request ,Exception e) throws Exception {
  18.  
    e.printStackTrace();
  19.  
     
  20.  
    return e.getMessage();
  21.  
    }
  22.  
    }

乍一眼看上去毫无问题,但这里有一个纰漏,由于Exception是异常的父类,如果你的项目中出现过在自定义异常中使用@ResponseStatus的情况,你的初衷是碰到那个自定义异常响应对应的状态码,而这个控制器增强处理类,会首先进入,并直接返回,不会再有@ResponseStatus的事情了,这里为了解决这种纰漏,我提供了一种解决方式。

  1.  
    package com.somnus.advice;
  2.  
     
  3.  
    import javax.servlet.http.HttpServletRequest;
  4.  
     
  5.  
    import org.springframework.core.annotation.AnnotationUtils;
  6.  
    import org.springframework.web.bind.annotation.ControllerAdvice;
  7.  
    import org.springframework.web.bind.annotation.ExceptionHandler;
  8.  
    import org.springframework.web.bind.annotation.ResponseBody;
  9.  
    import org.springframework.web.bind.annotation.ResponseStatus;
  10.  
     
  11.  
    @ControllerAdvice
  12.  
    public class ExceptionAdvice {
  13.  
     
  14.  
     
  15.  
    @ExceptionHandler({ Exception.class })
  16.  
    @ResponseBody
  17.  
    public String handException(HttpServletRequest request ,Exception e) throws Exception {
  18.  
    e.printStackTrace();
  19.  
    //If the exception is annotated with @ResponseStatus rethrow it and let
  20.  
    // the framework handle it - like the OrderNotFoundException example
  21.  
    // at the start of this post.
  22.  
    // AnnotationUtils is a Spring Framework utility class.
  23.  
    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
  24.  
    throw e;
  25.  
    }
  26.  
    // Otherwise setup and send the user to a default error-view.
  27.  
    /*ModelAndView mav = new ModelAndView();
  28.  
    mav.addObject("exception", e);
  29.  
    mav.addObject("url", request.getRequestURL());
  30.  
    mav.setViewName(DEFAULT_ERROR_VIEW);
  31.  
    return mav;*/
  32.  
    return e.getMessage();
  33.  
    }
  34.  
     
  35.  
    }

如果碰到了某个自定义异常加上了@ResponseStatus,就继续抛出,这样就不会让自定义异常失去加上@ResponseStatus的初衷

原文出处https://blog.csdn.net/w372426096/article/details/78429141

@ControllerAdvice详解的更多相关文章

  1. Spring MVC之@ControllerAdvice详解

    本文链接:https://blog.csdn.net/zxfryp909012366/article/details/82955259   对于@ControllerAdvice,我们比较熟知的用法是 ...

  2. springboot 详解RestControllerAdvice(ControllerAdvice)(转)

    springboot 详解RestControllerAdvice(ControllerAdvice)拦截异常并统一处理简介 @Target({ElementType.TYPE}) @Retentio ...

  3. SpringMVC异常处理机制详解[附带源码分析]

    目录 前言 重要接口和类介绍 HandlerExceptionResolver接口 AbstractHandlerExceptionResolver抽象类 AbstractHandlerMethodE ...

  4. JAVA基础——异常详解

    JAVA异常与异常处理详解 一.异常简介 什么是异常? 异常就是有异于常态,和正常情况不一样,有错误出错.在java中,阻止当前方法或作用域的情况,称之为异常. java中异常的体系是怎么样的呢? 1 ...

  5. Spring Boot 注解详解

    一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguration ...

  6. java基础(十五)----- Java 最全异常详解 ——Java高级开发必须懂的

    本文将详解java中的异常和异常处理机制 异常简介 什么是异常? 程序运行时,发生的不被期望的事件,它阻止了程序按照程序员的预期正常执行,这就是异常. Java异常的分类和类结构图 1.Java中的所 ...

  7. 【docker-compose】使用docker-compose部署运行spring boot+mysql 【处理容器的时区问题】【详解】【福利:使用docker-compose构建 wordpress+mysql】

    ==================================================================================================== ...

  8. 2017.2.13 开涛shiro教程-第十二章-与Spring集成(一)配置文件详解

    原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 第十二章-与Spring集成(一)配置文件详解 1.pom.xml ...

  9. SPRINGBOOT注解最全详解(

    #     SPRINGBOOT注解最全详解(整合超详细版本)          使用注解的优势:               1.采用纯java代码,不在需要配置繁杂的xml文件           ...

随机推荐

  1. TensorFlow-GPU+cuda8+cudnn6+anaconda安装遇到的版本错误

    第一遍装的时候是cuda10+cudnn5.1这个诡异的组合,失败 卸载cuda就是把所有的NVIDIA有关的应用都删掉,c盘文件也都删掉,不用留. 第二遍是cuda8+cudnn5.1.版本还是对不 ...

  2. [转][SerialPort]测试用例

    private void Form1_Load(object sender, EventArgs e) { var s = SerialPort.GetPortNames().OrderBy(r =& ...

  3. 20175236 2018-2019-2 《Java程序设计》第五周学习总结

    教材学习内容总结 接口回调 1.接口属于引用型变量,可以存放实现该接口类的实例的引用,即存放对象的引用. 2.接口回调理解上跟对象的上转型对象差不多. 理解接口 接口可以抽象出重要的行为标准. 接口多 ...

  4. laravel-admin挖坑之旅

    1.git-bash下使用命令php artisan admin:make UserController --model=App\User会报错Model does not exists 要加多一个“ ...

  5. ArcGIS紧凑型缓存存储格式分析

    by 蔡建良 2018-8-24 网络中我看到的网文将bundle存储切片数据的方式都没说清或是说错.按照错误方法一样可以在桌面浏览,但在arcgis for android却无法浏览. bundlx ...

  6. ibatis.net 循环

    if (oReqV[0]["tag"] != null && !string.IsNullOrEmpty(oReqV[0]["tag"].ToS ...

  7. sass 和less 分别在循环 和超出省略方面的区别!

    这两天在迁项目,新项目支持less预处理器,之前是采用的sass,就出现一些冲突,好在有对应的转换方式,重点说下 我遇到的2个问题 1:超出省略 sass: 声明: 在需要的地方: less: 在使用 ...

  8. spark2.1源码分析2:从SparkPi分析一个job的执行

    从SparkPi的一个行动操作入手,选择Run–Debug SparkPi进入调试: F8:Step Over F7:Step Into 右键Run to Cursor Ctrl+B 查看定义 导航– ...

  9. 取消win10 任务栏已固定的软件

    通过组策略编辑器 设置为“已禁用”,就可 ,自由取消已固定的图标.

  10. 微信小程序支付+php后端

    最近在做自有项目后端用的是thinkphp5.1框架,闲话不说直接上代码 小程序代码 wxpay: function(e){ let thisid = e.currentTarget.dataset. ...