@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的更多相关文章

  1. SpringMVC异常处理注解@ExceptionHandler@ControllerAdvice@ResponseStatus

    参考: http://blog.csdn.net/w372426096/article/details/78429132 http://blog.csdn.net/w372426096/article ...

  2. Spring3.2新注解@ControllerAdvice

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

  3. springBoot注解大全JPA注解springMVC相关注解全局异常处理

    https://www.cnblogs.com/tanwei81/p/6814022.html 一.注解(annotations)列表 @SpringBootApplication:包含了@Compo ...

  4. Spring 和 SpringMVC 常用注解和配置(@Autowired、@Resource、@Component、@Repository、@Service、@Controller的区别)

    Spring 常用注解 总结内容 一.Spring部分 1.声明bean的注解 2.注入bean的注解 3.java配置类相关注解 4.切面(AOP)相关注解 5.事务注解 6.@Bean的属性支持 ...

  5. SpringMVC常用注解實例詳解3:@ResponseBody

    我的開發環境框架:        springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...

  6. SpringMVC常用注解實例詳解2:@ModelAttribute

    我的開發環境框架:        springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...

  7. springMVC的注解详解

    springmvc常用注解标签详解 1.@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业 ...

  8. springmvc常用注解与类型转换

    springmvc常用注解与类型转换 一:前置 spring -servlet.xml 注入 <!-- 启用spring mvc 注解 --> <context:annotation ...

  9. springMvc的注解注入方式

    springMvc的注解注入方式 最近在看springMvc的源码,看到了该框架的注入注解的部分觉的有点吃力,可能还是对注解的方面的知识还认识的不够深刻,所以特意去学习注解方面的知识.由于本人也是抱着 ...

随机推荐

  1. xshell5运行hadoop集群

    ---恢复内容开始--- 1.CentOS主机配置 在配置Hadoop过程中,防火墙必须优先关闭SELinux,否则将影响后续Hadoop配置与使用,命令如下: # 查看 “系统防火墙” 状态命令 s ...

  2. [数据结构与算法] 字符串匹配 - BF算法

    BF(Brute Force)算法 又称暴力匹配算法,是一种朴素的模式匹配算法 给定主串 S : Bilibili 和子串 T :Bilididi 步骤: 1. 主串 S 第一位开始与子串 T 第一位 ...

  3. 防止xss攻击的前端的方法

    项目当中在进行安全测试的时候,遇到了xss的攻击,要求前端来做个防御,针对于遇到的xss攻击,做个总结 1.xss---存储型xss的攻击 前端只要在接收到后台数据的时候做个特殊字符的过滤,即可抵制攻 ...

  4. AtCoder abc 141 F - Xor Sum 3(线性基)

    传送门 题意: 给出\(n\)个数\(a_i\),现在要将其分为两堆,使得这两堆数的异或和相加最大. 思路: 考虑线性基贪心求解. 但直接上线性基求出一组的答案是行不通的,原因之后会说. 注意到如果二 ...

  5. Ninja——小而快的构建系统

    介绍 Ninja 是Google的一名程序员推出的注重速度的构建工具,一般在Unix/Linux上的程序通过make/makefile来构建编译,而Ninja通过将编译任务并行组织,大大提高了构建速度 ...

  6. Celery详解(2)

    除了redis,还可以使用另外一个神器----Celery.Celery是一个异步任务的调度工具. Celery是Distributed Task Queue,分布式任务队列,分布式决定了可以有多个w ...

  7. android onActivityResult不被回调或窗体弹出后即补回调的解决办法

    假设从A窗体弹出B窗体,则在AndroidManifest.xml文件中,B不能有:android:launchMode="singleTask“属性,否则,A窗体里的onActivityR ...

  8. 使用Windows api 获得系统时间并生成文件夹

    // 使用window api 获得系统时间 // 生成 #include "stdafx.h" #include <Windows.h> #include <d ...

  9. 以opencv320和vs2013为例说明 vs路径配置方法

    =========================================== 新方法 ======================= 新方法的配置过程,路径之类的设置都是一样. 区别在于,在 ...

  10. Docker常用命令(五)

    一.帮助命令 docker version docker info # 重要 docker --help 可以使用docker COMMAND --help 查看某个命令具体如何使用. 二.镜像命令 ...