springMvc中@ControllerAdvice的使用

@ControllerAdvice是一个@Component,用于定义@ExceptionHandler@InitBinder@ModelAttribute方法,适用于所有使用@RequestMapping方法。

通常情况下配合@ExceptionHandler使用

springMvc中如果单使用@ExceptionHandler,只能在当前Controller中处理异常。但当配合@ControllerAdvice一起使用的时候,就可以摆脱那个限制了。

代码:

springMvc中@ControllerAdvice的使用

这样只要在要处理异常的代码逻辑中加入throw new RuntimeException();即会走exceptionHandler这个方法!并返回页面