Spring MVC 4升级至Spring MVC 5报404错误,求完整迁移校验步骤
Spring MVC 4 升级 5(XML配置项目)迁移指南及404问题修复方案
注意:纯XML配置的项目无需搭配Java配置的@EnableWebMvc注解,二者同时启用会导致Spring MVC上下文重复配置,反而出现映射失效问题,仅需正确配置XML中的<mvc:annotation-driven />即可
404错误核心修复点
当前你遇到的No mapping found for GET request问题,90%以上是Spring 5对路径匹配规则的默认调整导致的,可按以下顺序排查修复:
- 确认Spring MVC XML配置中已添加
<mvc:annotation-driven />节点,同时XML头部的mvc命名空间需匹配5.x版本,不要写死旧版4.x的xsd地址,示例配置如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 启用注解驱动,注册@RequestMapping等注解的映射处理器 --> <mvc:annotation-driven /> <!-- 恢复Spring 4的默认路径匹配规则,解决404核心问题:开启后缀匹配、尾部斜杠匹配 --> <mvc:path-matching suffix-pattern="true" trailing-slash-match="true" /> <!-- 确保controller包被正确扫描 --> <context:component-scan base-package="你的项目controller包路径" /> </beans>
- 检查
<context:component-scan />的base-package路径是否覆盖所有带@Controller注解的类,Spring 5对组件扫描的过滤规则更严格,避免漏扫控制器 - 检查web.xml中
DispatcherServlet的映射规则,如果用了后缀匹配(如*.do),确保没有和其他servlet的映射规则冲突
分步迁移最佳实践
- 第一步:统一依赖版本,所有Spring相关依赖(spring-core、spring-webmvc、spring-context、spring-jdbc等)全部升级到同一5.x稳定版本,彻底移除所有4.x版本的依赖,避免跨版本冲突
- 第二步:清理所有XML配置的命名空间,删除xsd地址中的版本号(如
spring-mvc-4.3.xsd改为spring-mvc.xsd),Spring会自动匹配当前使用的版本规则 - 第三步:调整路径匹配规则,如需兼容旧版请求路径,按上述示例配置
<mvc:path-matching />节点 - 第四步:校验静态资源映射,如果你配置了
<mvc:resources />处理静态资源,确认映射路径和新版路径规则无冲突 - 第五步:适配拦截器、异常处理逻辑,检查
<mvc:interceptors>配置的拦截器、@ControllerAdvice注解的全局异常类是否正常生效 - 第六步:功能回归测试,优先测试核心接口的请求、参数绑定、视图返回是否正常
迁移完成校验检查点
- 所有HTTP方法(GET/POST/PUT/DELETE)的接口请求无404、405错误
- 静态资源(js、css、图片、文件等)可正常访问
- 控制器参数绑定(
@RequestParam/@PathVariable/@RequestBody)功能正常 - 视图解析器可正常返回前端页面,无404错误
- 拦截器、全局异常处理、文件上传等扩展功能正常
- 项目启动日志无Spring相关的WARN、ERROR级别的异常信息
内容的提问来源于stack exchange,提问作者DDas
相关产品推荐
相关产品推荐

