@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的初衷
原文出处https://blog.csdn.net/w372426096/article/details/78429141
@ControllerAdvice详解的更多相关文章
- Spring MVC之@ControllerAdvice详解
本文链接:https://blog.csdn.net/zxfryp909012366/article/details/82955259 对于@ControllerAdvice,我们比较熟知的用法是 ...
- springboot 详解RestControllerAdvice(ControllerAdvice)(转)
springboot 详解RestControllerAdvice(ControllerAdvice)拦截异常并统一处理简介 @Target({ElementType.TYPE}) @Retentio ...
- SpringMVC异常处理机制详解[附带源码分析]
目录 前言 重要接口和类介绍 HandlerExceptionResolver接口 AbstractHandlerExceptionResolver抽象类 AbstractHandlerMethodE ...
- JAVA基础——异常详解
JAVA异常与异常处理详解 一.异常简介 什么是异常? 异常就是有异于常态,和正常情况不一样,有错误出错.在java中,阻止当前方法或作用域的情况,称之为异常. java中异常的体系是怎么样的呢? 1 ...
- Spring Boot 注解详解
一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguration ...
- java基础(十五)----- Java 最全异常详解 ——Java高级开发必须懂的
本文将详解java中的异常和异常处理机制 异常简介 什么是异常? 程序运行时,发生的不被期望的事件,它阻止了程序按照程序员的预期正常执行,这就是异常. Java异常的分类和类结构图 1.Java中的所 ...
- 【docker-compose】使用docker-compose部署运行spring boot+mysql 【处理容器的时区问题】【详解】【福利:使用docker-compose构建 wordpress+mysql】
==================================================================================================== ...
- 2017.2.13 开涛shiro教程-第十二章-与Spring集成(一)配置文件详解
原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 第十二章-与Spring集成(一)配置文件详解 1.pom.xml ...
- SPRINGBOOT注解最全详解(
# SPRINGBOOT注解最全详解(整合超详细版本) 使用注解的优势: 1.采用纯java代码,不在需要配置繁杂的xml文件 ...
随机推荐
- ssh方式请求gitlab需要密码解决方法
问题:gitlab是使用docker安装的,配置好公钥私钥后,请求gitlab一直需要输入密码,而且这个密码输入什么都不对. 原因:后来发现是因为docker做了端口映射,如使用宿主机的10022映射 ...
- git切换远程仓库地址
$ git remote -vorigin http://192.168.1.100/aaa/Project.git (fetch)origin http://192.168.1.100/aaa ...
- .net core2.1 配置
ASPNETCORE_ENVIRONMENT Development(开发)Staging(预演)Production(生产) var builder = new ConfigurationBuild ...
- [STM32F103]RTC日历
使能PWR和BKP时钟: a) RCC_APB1PeriphClockCmd(); 使能后备寄存器访问: a) PWR_BackupAccessCmd(); 配置RTC时钟源,使能RTC时钟: a) ...
- Problem B: 故障电灯(light)
考虑对电灯进行差分:若第i个电灯和第i + 1个电灯状态不同,则在第i个位置上放一个球 这样我们就放置了不超过2n个球,且必然是偶数个 于是问题转化为:有m个球,每一步可以把一个球平移奇质数个位置,两 ...
- LeetCode1-5题
1.两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个 ...
- PHP语言入门的学习方法十要素
对于PHP程序设计语言来说.每个人的学习方式不同,写这篇文章的目的是分享一下自己的学习过程,仅供参考,不要一味的用别人的学习方法,找对自己有用的学习方式.经常在某些论坛和QQ群里看到一些朋友会问“怎样 ...
- 列举spark所有算子
一.RDD概述 1.什么是RDD RDD(Resilient Distributed Dataset)叫做弹性分布式数据集,是Spark中最基本的数据抽象,它代表一个不可 ...
- Java 转JSON串
一.JSON (JavaScript Object Notation) 1.轻量级数据交换格式能够替代XML的工作 2.数据格式比较简单, 易于读写, 格式都是压缩的, 占用带宽小(简洁.简单.体积小 ...
- NFS存储服务
NFS存储服务笔记======================================================================NFS共享存储是什么: 英文名-Netwo ...