You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.0.0+重写ResponseEntityExceptionHandler方法报错问题

解决重写handleMethodArgumentNotValid时的“未覆盖父类方法”错误

出现这个错误的核心原因是你的方法签名和父类ResponseEntityExceptionHandler中的对应方法不匹配,常见场景和解决办法如下:

1. Spring Boot 3.x(对应Spring 6+)版本不兼容

Spring 6.x开始,ResponseEntityExceptionHandler的handleMethodArgumentNotValid方法第三个参数从HttpStatus改成了HttpStatusCode,你的代码用了旧的参数类型,导致无法识别为重写方法。

修改方法签名,把第三个参数换成HttpStatusCode即可,返回时依然可以用HttpStatus.BAD_REQUEST(它是HttpStatusCode的实现类):

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
    MethodArgumentNotValidException ex, HttpHeaders headers,
    HttpStatusCode status, WebRequest request) {

  Map<String, List<String>> body = new HashMap<>();

  List<String> errors = ex.getBindingResult()
      .getFieldErrors()
      .stream()
      .map(DefaultMessageSourceResolvable::getDefaultMessage)
      .collect(Collectors.toList());

  body.put("errors", errors);

  return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}

2. Spring Boot 2.x及以下版本的排查点

  • 检查方法签名的参数顺序、类型是否和父类完全一致:父类方法的参数顺序是MethodArgumentNotValidException → HttpHeaders → HttpStatus → WebRequest,不能搞混。
  • 确认导入的ResponseEntityExceptionHandler包正确:必须是org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler,别导错其他包的类。
  • 清理IDE缓存:比如IntelliJ可以通过File → Invalidate Caches/Restart刷新缓存,有时候IDE会误报。

内容的提问来源于stack exchange,提问作者Gianni Spear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:27:24