顾名思义,@ControllerAdvice
就是 @Controller
的增强版。@ControllerAdvice
主要用来处理全局数据, 一般搭配 @ExceptionHandler
、@ModelAttribute
以及 @InitBinder
使用。
处理全局异常
@ControllerAdvice
最常见的使用场景就是全局异常处理。例如用户上传的文件超过了限制大小,就会抛出异常,此时可以通过 @ControllerAdvice
结合 @ExceptionHandler
定义全局异常捕获机制,只需在系统中定义 CustomExceptionHandler 类(名字不限),然后添加 @ControllerAdvice
注解即可。也可以通过 assignableTypes
指定特定的 Controller
类,让异常处理类只处理特定类抛出的异常:
@ControllerAdvice(assignableTypes = {
ExceptionController.class})
当系统启动时,该类就会被扫描到 Spring 容器中,然后定义 uploadException 方法(名字不限),在该方法上添加了 @ExceptionHandler
注解,其中定义的 MaxUploadSizeExceededException.class
表明该方法用来处理 MaxUploadSizeExceededException
类型的异常。如果想让该方法处理所有类型的异常,只需将 MaxUploadSizeExceededException
改为 Exception
即可 。方法的参数可以有异常实例、 HttpServletResponse
以 及 HttpServletRequest
、 Model
等 , 返回值可以是一段 JSON 、一 个ModelAndView
、 一个逻辑视图名等。代码如下:
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org