Spring注解@ControllerAdvice

系统管理员 2022-04-01 04:26 340阅读 0赞

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

  1. package org.springframework.web.bind.annotation;
  2. @Target(ElementType.TYPE)
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Documented
  5. @Component
  6. public @interface ControllerAdvice {
  7. @AliasFor("basePackages")
  8. String[] value() default { };
  9. @AliasFor("value")
  10. String[] basePackages() default { };
  11. Class<?>[] basePackageClasses() default { };
  12. Class<?>[] assignableTypes() default { };
  13. 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最有用,其它两个不常用。
@ControllerAdvice用来处理异常
在SpringMVC重要注解(一)@ExceptionHandler和@ResponseStatus我们提到,如果单使用@ExceptionHandler,只能在当前Controller中处理异常。但当配合@ControllerAdvice一起使用的时候,就可以摆脱那个限制了。

  1. package com.somnus.advice;
  2. import org.springframework.web.bind.annotation.ControllerAdvice;
  3. import org.springframework.web.bind.annotation.ExceptionHandler;
  4. import org.springframework.web.bind.annotation.ResponseBody;
  5. @ControllerAdvice
  6. public class ExceptionAdvice {
  7. @ExceptionHandler({ ArrayIndexOutOfBoundsException.class })
  8. @ResponseBody
  9. public String handleArrayIndexOutOfBoundsException(Exception e) {
  10. e.printStackTrace();
  11. return "testArrayIndexOutOfBoundsException";
  12. }
  13. }
  14. @Controller
  15. @RequestMapping(value = "exception")
  16. public class ExceptionHandlerController {
  17. @RequestMapping(value = "e2/{id}", method = { RequestMethod.GET })
  18. @ResponseBody
  19. public String testExceptionHandle2(@PathVariable(value = "id") Integer id) {
  20. List<String> list = Arrays.asList(new String[]{ "a","b","c","d"});
  21. return list.get(id-1);
  22. }
  23. }

当我们访问http://localhost:8080/SpringMVC/exception/e2/5的时候会抛出ArrayIndexOutOfBoundsException异常,这时候定义在@ControllerAdvice中的@ExceptionHandler就开始发挥作用了。

如果我们想定义一个处理全局的异常

  1. package com.somnus.advice;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.core.annotation.AnnotationUtils;
  4. import org.springframework.web.bind.annotation.ControllerAdvice;
  5. import org.springframework.web.bind.annotation.ExceptionHandler;
  6. import org.springframework.web.bind.annotation.ResponseBody;
  7. import org.springframework.web.bind.annotation.ResponseStatus;
  8. @ControllerAdvice
  9. public class ExceptionAdvice {
  10. @ExceptionHandler({ Exception.class })
  11. @ResponseBody
  12. public String handException(HttpServletRequest request ,Exception e) throws Exception {
  13. e.printStackTrace();
  14. return e.getMessage();
  15. }
  16. }

乍一眼看上去毫无问题,但这里有一个纰漏,由于Exception是异常的父类,如果你的项目中出现过在自定义异常中使用@ResponseStatus的情况,你的初衷是碰到那个自定义异常响应对应的状态码,而这个控制器增强处理类,会首先进入,并直接返回,不会再有@ResponseStatus的事情了,这里为了解决这种纰漏,我提供了一种解决方式。

  1. package com.somnus.advice;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.core.annotation.AnnotationUtils;
  4. import org.springframework.web.bind.annotation.ControllerAdvice;
  5. import org.springframework.web.bind.annotation.ExceptionHandler;
  6. import org.springframework.web.bind.annotation.ResponseBody;
  7. import org.springframework.web.bind.annotation.ResponseStatus;
  8. @ControllerAdvice
  9. public class ExceptionAdvice {
  10. @ExceptionHandler({ Exception.class })
  11. @ResponseBody
  12. public String handException(HttpServletRequest request ,Exception e) throws Exception {
  13. e.printStackTrace();
  14. //If the exception is annotated with @ResponseStatus rethrow it and let
  15. // the framework handle it - like the OrderNotFoundException example
  16. // at the start of this post.
  17. // AnnotationUtils is a Spring Framework utility class.
  18. if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
  19. throw e;
  20. }
  21. // Otherwise setup and send the user to a default error-view.
  22. /*ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", request.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav;*/
  23. return e.getMessage();
  24. }
  25. }

如果碰到了某个自定义异常加上了@ResponseStatus,就继续抛出,这样就不会让自定义异常失去加上@ResponseStatus的初衷。

发表评论

表情:
评论列表 (有 0 条评论,340人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ControllerAdvice注解的使用

    为了方便对异常的统一管理,spring mvc提供了ControllerAdvice注解对异常进行统一的处理,拿到这些异常信息后,可以做一些处理,比如提供一个统一的web界面查