一、简介

@ControllerAdvice,是spring3.2提供的新注解,意思是控制器增强。

下面是它的解释。

大致意思是,

1、表示标有这个注解的类是一个Controller。它有一个默认行为:被注解的类会作用到所有已知的Controller上。

2、它通常会和 @ExceptionHandler @InitBinder @ModelAttribute 等注解一起使用

/**
* Indicates the annotated class assists a "Controller".
*
* <p>Serves as a specialization of {@link Component @Component}, allowing for
* implementation classes to be autodetected through classpath scanning.
*
* <p>It is typically used to define {@link ExceptionHandler @ExceptionHandler},
* {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
* methods that apply to all {@link RequestMapping @RequestMapping} methods.
*
* <p>One of {@link #annotations()}, {@link #basePackageClasses()},
* {@link #basePackages()} or its alias {@link #value()}
* may be specified to define specific subsets of Controllers
* to assist. When multiple selectors are applied, OR logic is applied -
* meaning selected Controllers should match at least one selector.
*
* <p>The default behavior (i.e. if used without any selector),
* the {@code @ControllerAdvice} annotated class will
* assist all known Controllers.
*
* <p>Note that those checks are done at runtime, so adding many attributes and using
* multiple strategies may have negative impacts (complexity, performance).
*
* @author Rossen Stoyanchev
* @author Brian Clozel
* @author Sam Brannen
* @since 3.2
*/

在项目中与 @ExceptionHandler 一起使用的情况会比较多。

下面是@ExceptionHandler 的解释。

只截取了一部分,大致意思就是@ExceptionHandler标注的类或者方法是一个异常处理类或者方法。

它非常灵活,可以使用value指定具体的异常类。

/**
* Annotation for handling exceptions in specific handler classes and/or
* handler methods. Provides consistent style between Servlet and Portlet
* environments, with the semantics adapting to the concrete environment.
*
* <p>Handler methods which are annotated with this annotation are allowed to
* have very flexible signatures. They may have parameters of the following
* types, in arbitrary order:
* <ul>
* <li>An exception argument: declared as a general Exception or as a more
* specific exception. This also serves as a mapping hint if the annotation
* itself does not narrow the exception types through its {@link #value()}.
* <li>Request and/or response objects (Servlet API or Portlet API).
* You may choose any specific request/response type, e.g.
* {@link javax.servlet.ServletRequest} / {@link javax.servlet.http.HttpServletRequest}
* or {@link javax.portlet.PortletRequest} / {@link javax.portlet.ActionRequest} /
* {@link javax.portlet.RenderRequest}. Note that in the Portlet case,
* an explicitly declared action/render argument is also used for mapping
* specific request types onto a handler method (in case of no other
* information given that differentiates between action and render requests).
* <li>Session object (Servlet API or Portlet API): either
* {@link javax.servlet.http.HttpSession} or {@link javax.portlet.PortletSession}.
* An argument of this type will enforce the presence of a corresponding session.
* As a consequence, such an argument will never be {@code null}.
* <i>Note that session access may not be thread-safe, in particular in a
* Servlet environment: Consider switching the
* {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#setSynchronizeOnSession
* "synchronizeOnSession"} flag to "true" if multiple requests are allowed to
* access a session concurrently.</i>
* <li>{@link org.springframework.web.context.request.WebRequest} or
* {@link org.springframework.web.context.request.NativeWebRequest}.
* Allows for generic request parameter access as well as request/session
* attribute access, without ties to the native Servlet/Portlet API.
* <li>{@link java.util.Locale} for the current request locale
* (determined by the most specific locale resolver available,
* i.e. the configured {@link org.springframework.web.servlet.LocaleResolver}
* in a Servlet environment and the portal locale in a Portlet environment).
* <li>{@link java.io.InputStream} / {@link java.io.Reader} for access
* to the request's content. This will be the raw InputStream/Reader as
* exposed by the Servlet/Portlet API.
* <li>{@link java.io.OutputStream} / {@link java.io.Writer} for generating
* the response's content. This will be the raw OutputStream/Writer as
* exposed by the Servlet/Portlet API.
* <li>{@link org.springframework.ui.Model} as an alternative to returning
* a model map from the handler method. Note that the provided model is not
* pre-populated with regular model attributes and therefore always empty,
* as a convenience for preparing the model for an exception-specific view.
* </ul>
* ......
*

二、实践

下面这段代码是我们项目中使用到的。用于处理业务中抛出自定义的异常ServiceException与通用异常的。

/**
* 全局的业务异常处理类.
*
* @author lkb
*/
@ControllerAdvice
public class GlobalExceptionHandler
{ /** The error code. */
@Value("${errorCode:ERROR_10001}")
private String errorCode; /**
* 发生自定义业务异常时处理方法.
*
* @param req the req
* @param e the e
* @return the string
* @throws Exception 从每个模块control获取,另外JSON格式从定义文档获取
*/
@ExceptionHandler(value = ServiceException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public String defaultErrorHandler(HttpServletRequest req, ServiceException e)
throws Exception
{
LogUtil.getInstance().error("+++++++++++++ServiceException Error Info+++++++++++++", e);
//实例化异常对象
ErrorInfo errorInfo = new ErrorInfo();
if (e != null && StringUtils.isNotEmpty(e.getMessage()))
{
errorInfo.setErrorCode(e.getMessage());
errorInfo.setErrorDesc("");
errorInfo.setErrorInfoUrl("");
}
Map<String, Object> resultMap = CommonUtil.getInstance().getErrorData(errorInfo);
return JSON.toJSONString(resultMap);
} /**
* 发生非业务异常时处理方法.
*
* @param req the req
* @param e the e
* @return the string
* @throws Exception 未知异常,在配置文件定义;默认在上面定义接收
*/
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
//@ResponseStatus()
@ResponseBody
public String defaultErrorHandler(HttpServletRequest req, Exception e)
throws Exception
{
LogUtil.getInstance().error("+++++++++++++Exception Error Info+++++++++++++", e);
//实例化异常对象
ErrorInfo errorInfo = new ErrorInfo();
errorInfo.setErrorCode(errorCode);
errorInfo.setErrorDesc("");
errorInfo.setErrorInfoUrl("");
Map<String, Object> resultMap = CommonUtil.getInstance().getErrorData(errorInfo);
return JSON.toJSONString(resultMap);
}
}

@ControllerAdvice + @ExceptionHandler 使用的更多相关文章

  1. spring mvc统一异常处理(@ControllerAdvice + @ExceptionHandler)

    spring 封装了非常强大的异常处理机制.本文选取@ControllerAdvice + @ExceptionHandler 这种零配置(全注解),作为异常处理解决方案! @ControllerAd ...

  2. @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常==》记录

    对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...

  3. 转:@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

    继承 ResponseEntityExceptionHandler 类来实现针对 Rest 接口 的全局异常捕获,并且可以返回自定义格式: 复制代码 1 @Slf4j 2 @ControllerAdv ...

  4. (转)springboot全局处理异常(@ControllerAdvice + @ExceptionHandler)

    1.@ControllerAdvice 1.场景一 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": ...

  5. Spring @ControllerAdvice @ExceptionHandler 全局处理异常

    对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...

  6. 【统一异常处理】@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

    1.利用springmvc注解对Controller层异常全局处理 对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service ...

  7. 十四、springboot全局处理异常(@ControllerAdvice + @ExceptionHandler)

    1.@ControllerAdvice 1.场景一 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": ...

  8. SpringBoot入门教程(十九)@ControllerAdvice+@ExceptionHandler全局捕获Controller异常

    在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@ModelAttribute,并应用到所有@Requ ...

  9. @ControllerAdvice+@ExceptionHandler处理架构异常捕获

    1.注解引入 1) @ControllerAdvice - 控制器增强 @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) ...

  10. @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

    @ControllerAdvice 和 @ExceptionHandler 的区别 ExceptionHandler, 方法注解, 作用于 Controller 级别. ExceptionHandle ...

随机推荐

  1. Java 使用 Enum 实现单例模式

    在这篇文章中介绍了单例模式有五种写法:懒汉.饿汉.双重检验锁.静态内部类.枚举.如果涉及到反序列化创建对象时推荐使用枚举的方式来实现单例,因为Enum能防止反序列化时重新创建新的对象.本文介绍 Enu ...

  2. C++ new动态数组初始化

    strlen函数是不包括‘\0’的长度的,sizeof计算的结果才包括'\0'的长度: C++ new动态数组初始化void testnew( const char* str ) { if (!str ...

  3. UDP ------ UDP打洞

    为什么需要UDP打洞 处于两个不同局域网的主机不能直接进行UDP通信 UDP"打洞"原理 1.       NAT分类 根据Stun协议(RFC3489),NAT大致分为下面四类 ...

  4. MingW-v4.8.0+EDE-v13.04 配置使用C语言图形库

    From: http://www.cnblogs.com/killerlegend/p/3946768.html Author:KillerLegend Date:2014.8.30 MingW的配置 ...

  5. 数学:拓展Lucas定理

    拓展Lucas定理解决大组合数取模并且模数为任意数的情况 大概的思路是把模数用唯一分解定理拆开之后然后去做 然后要解决的一个子问题是求模质数的k次方 将分母部分转化成逆元再去做就好了 这里贴一份别人的 ...

  6. SimpleRoundedImage-不使用mask实现圆角矩形图片

    1.一张图片是如何显示在屏幕上的 一张图片渲染到unity界面中的大致流程. 2.我们要做什么 我们要做的就是在CPU中将图片的矩形顶点数据修改成圆角矩形的顶点信息,之后Unity会将修改后的顶点数据 ...

  7. ant+sonar+jacoco代码质量代码覆盖率扫描

    使用ant构建的java web项目如何做sonar代码质量扫描?以下就是实际遇到并成功使用的案例一.做sonar扫描的准备工作    1.给web项目增加build.xml构建脚本.    2.下载 ...

  8. Python3中的内置函数

    内置函数 我们一起来看看python里的内置函数.什么是内置函数?就是Python给你提供的,拿来直接用的函数,比如print,input等等.截止到python版本3.6.2,现在python一共为 ...

  9. Windows中用“ls”命令

    解决办法是: 在C:\Windows\System32目录下新建文本文档,文件内容为: @echo off dir 另存为“ls.bat” 类型为所有文件,编码ANSI 可使用dir 或者ls都可以 ...

  10. lucene删除索引——(五)

    增加在入门程序创建索引中,增删改用IndexWriter. 1.获取IndexWriter的代码 // public IndexWriter getIndexWriter() throws Excep ...