SpringMVC重要注解 @ControllerAdvice
@ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强。让我们先看看@ControllerAdvice的实现:
package org.springframework.web.bind.annotation; @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice { @AliasFor("basePackages")
String[] value() default {}; @AliasFor("value")
String[] basePackages() default {}; Class<?>[] basePackageClasses() default {}; Class<?>[] assignableTypes() default {}; Class<? extends Annotation>[] annotations() default {};
}
没什么特别之处,该注解使用@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一起使用的时候,就可以摆脱那个限制了。
package com.somnus.advice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice
public class ExceptionAdvice { @ExceptionHandler({ ArrayIndexOutOfBoundsException.class })
@ResponseBody
public String handleArrayIndexOutOfBoundsException(Exception e) {
e.printStackTrace();
return "testArrayIndexOutOfBoundsException";
@Controller
@RequestMapping(value = "exception")
public class ExceptionHandlerController { @RequestMapping(value = "e2/{id}", method = { RequestMethod.GET })
@ResponseBody
public String testExceptionHandle2(@PathVariable(value = "id") Integer id) {
List<String> list = Arrays.asList(new String[]{"a","b","c","d"});
return list.get(id-1);
} }
当我们访问http://localhost:8080/SpringMVC/exception/e2/5的时候会抛出ArrayIndexOutOfBoundsException异常,这时候定义在@ControllerAdvice中的@ExceptionHandler就开始发挥作用了。
如果我们想定义一个处理全局的异常
package com.somnus.advice;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler({ Exception.class })
@ResponseBody
public String handException(HttpServletRequest request ,Exception e) throws Exception {
e.printStackTrace();
return e.getMessage();
}
}
乍一眼看上去毫无问题,但这里有一个纰漏,由于Exception是异常的父类,如果你的项目中出现过在自定义异常中使用@ResponseStatus的情况,你的初衷是碰到那个自定义异常响应对应的状态码,而这个控制器增强处理类,会首先进入,并直接返回,不会再有@ResponseStatus的事情了,这里为了解决这种纰漏,我提供了一种解决方式。
package com.somnus.advice;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler({ Exception.class })
@ResponseBody
public String handException(HttpServletRequest request ,Exception e) throws Exception {
e.printStackTrace();
//If the exception is annotated with @ResponseStatus rethrow it and let
// the framework handle it - like the OrderNotFoundException example
// at the start of this post.
// AnnotationUtils is a Spring Framework utility class.
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
throw e;
}
// Otherwise setup and send the user to a default error-view.
/*ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName(DEFAULT_ERROR_VIEW);
return mav;*/
return e.getMessage();
}
}
如果碰到了某个自定义异常加上了@ResponseStatus,就继续抛出,这样就不会让自定义异常失去加上@ResponseStatus的初衷。
SpringMVC重要注解 @ControllerAdvice的更多相关文章
- SpringMVC异常处理注解@ExceptionHandler@ControllerAdvice@ResponseStatus
参考: http://blog.csdn.net/w372426096/article/details/78429132 http://blog.csdn.net/w372426096/article ...
- Spring3.2新注解@ControllerAdvice
Spring3.2新注解@ControllerAdvice @ControllerAdvice,是spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@Control ...
- springBoot注解大全JPA注解springMVC相关注解全局异常处理
https://www.cnblogs.com/tanwei81/p/6814022.html 一.注解(annotations)列表 @SpringBootApplication:包含了@Compo ...
- Spring 和 SpringMVC 常用注解和配置(@Autowired、@Resource、@Component、@Repository、@Service、@Controller的区别)
Spring 常用注解 总结内容 一.Spring部分 1.声明bean的注解 2.注入bean的注解 3.java配置类相关注解 4.切面(AOP)相关注解 5.事务注解 6.@Bean的属性支持 ...
- SpringMVC常用注解實例詳解3:@ResponseBody
我的開發環境框架: springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...
- SpringMVC常用注解實例詳解2:@ModelAttribute
我的開發環境框架: springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...
- springMVC的注解详解
springmvc常用注解标签详解 1.@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业 ...
- springmvc常用注解与类型转换
springmvc常用注解与类型转换 一:前置 spring -servlet.xml 注入 <!-- 启用spring mvc 注解 --> <context:annotation ...
- springMvc的注解注入方式
springMvc的注解注入方式 最近在看springMvc的源码,看到了该框架的注入注解的部分觉的有点吃力,可能还是对注解的方面的知识还认识的不够深刻,所以特意去学习注解方面的知识.由于本人也是抱着 ...
随机推荐
- Vue-组件模板抽离的写法
VUE的模板分离写法. 1.第一种(不常用) <script type="text/x-template" id="myCpm"> <div& ...
- MySQL的select(极客时间学习笔记)
查询语句 首先, 准备数据, 地址是: https://github.com/cystanford/sql_heros_data, 除了id以外, 24个字段的含义如下: 查询 查询分为单列查询, 多 ...
- git仓库的安装和基本使用
一.安装git软件 # yum install git -y 二.初始化git仓库 2.1 在git仓库的机器进行配置 # ifconfig eth0 | awk -F '[ :]+' 'NR==2 ...
- 01-人脸识别-基于MTCNN,框选人脸区域-detect_face_main
(本系列随笔持续更新) 搭建要求 详细的搭建过程在 参考资料1 中已经有啦. TensorFlow 1.6.0 OpenCV 2.4.8 仅仅是加载和读取图片的需要 Ubuntu 14.04 64bi ...
- python27期day09:函数的初始、函数的定义、函数的调用、函数的返回值、函数的参数、作业题。
1.函数的作用:封装代码.大量的减少了重复的代码. 2.全局空间:顶行写的就是全局空间. 图解 : 3.函数的定义: def 是一个关键字.申明要定义一个函数 my_len 函数的名字.遵循变量命名的 ...
- centos7 扩容
用 df -h, 看到磁盘满了 (注意:如果是二,或者第三次扩容,下面的参数就不一样) fdisk /dev/sda 但是失败了,显示没有多余的分区 可以看到 有个/dev/sda4 是我在这之前刚刚 ...
- 【电脑】分屏显示输入信号超出范围调整为XXXXXXX
选提示的那个范围就OK了. 注意:1.修改的是外界显示器,不是主显示器/笔记本. 2.修改外接显示器,不影响主显示器/笔记本
- 个人网站 & 博客
www.ykmimi.com (测试使用) http://www.implements.fun/ (测试使用) http://www.java-developer.cn/ (测试使用,预备论坛) ...
- git npm包管理
#Node # node 一.安装nodejs 下载地址:http://nodejs.cn/download/ 二.安装git 下载地址:https://git-scm.com/download/wi ...
- 前端性能优化&&网站性能优化
加载优化:1.合并css.JavaScript 2.合并小图片,使用精灵图 3.缓存一切可缓存的资源 4.使用长cache 5.使用外联式引用css.JavaScript 6.压缩HTML.CSS.J ...