Spring全局异常捕获是否基于AOP实现?底层原理探讨
Spring全局异常捕获是否基于AOP实现?
当我们使用@ControllerAdvice和@ExceptionHandler实现全局异常捕获时,是否意味着Spring内部采用了AOP技术?即Spring是否会在内部创建匹配所有@Controller或@RestController修饰方法的切点,切面为@Around或@AfterThrowing?还是说不存在这样的切点,而是由DispatcherServlet中的相关逻辑处理,当遇到异常时将其转交至对应的ExceptionHandler方法?
尽管提供的源码片段用于查找对应异常处理方法,但无法证明不存在切点,因此产生疑问:全局异常捕获是否使用AOP相关技术?它属于AOP范畴还是仅与Spring MVC相关?
示例代码
@ControllerAdvice @ResponseBody public class GlobalExceptionHandler { @ExceptionHandler(BaseException.class) public ResponseEntity<?> handleAppException(BaseException ex, HttpServletRequest request) { //... } @ExceptionHandler(value = ResourceNotFoundException.class) public ResponseEntity<ErrorReponse> handleResourceNotFoundException(ResourceNotFoundException ex, HttpServletRequest request) { //... } }
相关源码片段
@Nullable private Method getMappedMethod(Class<? extends Throwable> exceptionType) { List<Class<? extends Throwable>> matches = new ArrayList<>(); //Find all exception information that can be handled. MappedMethods stores the correspondence between exceptions and methods for handling exceptions for (Class<? extends Throwable> mappedException : this.mappedMethods.keySet()) { if (mappedException.isAssignableFrom(exceptionType)) { matches.add(mappedException); } } // If it is not empty, it means that there is a method to handle exceptions if (!matches.isEmpty()) { // Sort by matching degree from small to large matches.sort(new ExceptionDepthComparator(exceptionType)); // Return the method that handles the exception return this.mappedMethods.get(matches.get(0)); } else { return null; } }
解答
Spring的@ControllerAdvice+@ExceptionHandler全局异常捕获并没有基于AOP技术实现,它完全是Spring MVC自身的处理逻辑,和AOP范畴无关。
具体来说,Spring不会为所有Controller方法创建AOP切点或切面,整个流程由DispatcherServlet主导:
- 当Controller方法抛出异常后,DispatcherServlet不会直接返回错误,而是调用
HandlerExceptionResolver接口的实现类处理异常。 ExceptionHandlerExceptionResolver是专门负责处理@ExceptionHandler注解的实现类,它会提前扫描并缓存所有带有@ControllerAdvice和@ExceptionHandler的方法,建立异常类型到处理方法的映射关系(也就是你提供的源码里mappedMethods存储的内容)。- 当异常发生时,
ExceptionHandlerExceptionResolver通过getMappedMethod方法找到最匹配的异常处理方法,调用该方法生成响应返回给客户端。
这个机制是Spring MVC请求处理生命周期的一部分,依赖的是自身的异常解析器体系,而非AOP的切点、切面逻辑。
内容的提问来源于stack exchange,提问作者voi
相关产品推荐
相关产品推荐

