@ControllerAdvice 注解,会应用到所有的Controller中的@RequestMapping注解的方法中.

配置

要注意,经自己测试,这个注解的类,要被 org.springframework.web.servlet.DispatcherServletcontextConfigLocation中扫描到,如果是放在application context里扫描,是没有效果的.

java 文件内容

ControllerAdviceHandler.java

@ControllerAdvice
public class ControllerAdviceHandler {

    private static final Logger log = LoggerFactory.getLogger(ControllerAdviceHandler.class);

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        Map<String, Object> hello = new HashMap<>(2);
        hello.put("hello", "helllo msg");
        hello.put("msg", e.getMessage());
        log.error("error in url:{}, reason: {}", request.getRequestURI().toString(), e);
        return hello;
    }
}

xml 配置

DispatcherServletcontextconfigLocation参数值的配置文件里,添加以下:

	<mvc:annotation-driven />
	<!-- Scans for annotated @Controllers in the classpath -->
	<context:component-scan base-package="com.uniweibov2.web" use-default-filters="false">
   	    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	</context:component-scan>

    <!-- 启动对@AspectJ注解的支持 -->
	<aop:aspectj-autoproxy />
	<!--通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller-->
	<aop:aspectj-autoproxy proxy-target-class="true" />

使用

在某个Controller的拥有@RequestMapping注解的方法拥有抛出的异常:

    @RequestMapping("/index")
    @SystemControllerLog(module = FunctionBlockContants.SYSTEM, function = FunctionBlockContants.INDEX_PAGE)
    public ModelAndView index() {
        if (index.equals("login")) {
            throw new RuntimeException("error in index");
            //return new ModelAndView("redirect:/" + index);
        }
        return null;
        //return new ModelAndView(index);
    }

这样子,就会被@ControllerAdvice的类的@ExceptionHandler注解的方法处理异常了(比如,可以在这里记录log!)

示例

➜  ~  curl http://localhost:8080/index
{"msg":"error in index","hello":"helllo msg"}                                                                                                                                                      ➜  ~

控制台打印:

error in url:/index, reason: java.lang.RuntimeException: error in index