spring 30 @ControllerAdvice 之 @ExceptionHandler

演示

与之前的 @ControllerAdvice 中增强类似,分为控制器类中的懒惰解析,
和 @ControllerAdvice 注解标注的配置类中的,ExceptionHandlerExceptionResolver 初始化解析

点击查看代码
 public static void main(String[] args) throws NoSuchMethodException {
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();

//        ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver();
//        resolver.setMessageConverters(List.of(new MappingJackson2HttpMessageConverter()));
//        resolver.afterPropertiesSet();
        //被 spring 管理 实现了 `InitializingBean`接口 初始化时会回调 `afterPropertiesSet`方法
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);
        ExceptionHandlerExceptionResolver resolver = context.getBean(ExceptionHandlerExceptionResolver.class);
        
        HandlerMethod handlerMethod = new HandlerMethod(new Controller5(), Controller5.class.getMethod("foo"));
        Exception e = new Exception("e1");
        resolver.resolveException(request, response, handlerMethod, e);
        System.out.println(new String(response.getContentAsByteArray(), StandardCharsets.UTF_8));
    }

小结

  1. ExceptionHandlerExceptionResolver 初始化时会解析 @ControllerAdvice 中的 @ExceptionHandler 方法
  2. ExceptionHandlerExceptionResolver 会以类为单位,在该类首次处理异常时,解析此类的 @ExceptionHandler 方法
  3. 以上两种 @ExceptionHandler 的解析结果都会缓存来避免重复解析
  4. RequestMappingHandlerAdaptor 也会缓存结果,只不过多一点,initBinder RequestBodyAdvice ResponseBodyAdvice ModelAttribute ...
posted @ 2022-07-08 17:33  xy7112  阅读(39)  评论(0)    收藏  举报