Spring Boot 4.1 WAR 测试缺少 HttpMessageConverters,检查 providedRuntime 的 Tomcat 依赖
WAR 测试报 HttpMessageConverters 或 ServerBuilder 缺类时,检查 providedRuntime 是否错用了完整 Tomcat starter。按 Boot 4.1 的运行时依赖边界调整,并核对测试 classpath 与 WAR 部署。
WAR 项目使用 Spring Boot 4.1.1,已经引入 spring-boot-starter-webmvc-test,测试却报:
java.lang.ClassNotFoundException:
org.springframework.http.converter.HttpMessageConverters
有时缺失的是它的嵌套类 HttpMessageConverters$ServerBuilder。如果构建中把完整的 spring-boot-starter-tomcat 放进了 Gradle 的 providedRuntime,先核对这项依赖。补一个测试 starter,并不能保证被错误作用域带走的 Web 类重新进入测试运行路径。
这里限定使用 Gradle war 插件、部署到外部 Tomcat 的 Boot 4.1 项目。普通可执行 JAR 不需要照抄 WAR 的 provided 配置,旧 Boot 版本的依赖划分也不能直接套用。
看测试的实际 classpath
下面是会触发这条排查路径的依赖片段;保留工程原有的 Boot 版本管理和插件配置:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
}
在同一个模块中查看依赖,而不是检查本机缓存里有没有某个 JAR:
./gradlew dependencyInsight --dependency spring-web --configuration testRuntimeClasspath
多模块项目应在任务前加实际模块路径,例如 :web:dependencyInsight。Windows 使用 gradlew.bat。记录最终选中的 spring-web 版本及其依赖路径;如果查询没有找到它,异常与测试运行路径缺失相符。若它确实存在,要继续核对所选版本里是否包含报错类,以及测试是否通过另一套启动器运行。
HttpMessageConverters 存在于某个已下载的 JAR,不代表那个 JAR 已交给当前测试进程。手工把 JAR 复制到目录也不会修正 Gradle 的依赖配置。
providedRuntime 只声明 Tomcat runtime starter
Boot 4.1 的 WAR 配置应把这一行改成运行时专用的 starter:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat-runtime'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
}
两个 starter 的范围不同。完整的 Tomcat starter 还包含 Boot starter 和具有传递依赖的 Tomcat 模块;runtime starter 则限定容器运行时所需的组合。给外部容器准备 WAR 时,应使用该版本规定的运行时依赖边界,避免把应用需要的传递依赖一并归入 provided 范围。
不要同时留下两条 providedRuntime 来“保险”,也不要改成 compileOnly。后者不在测试 classpath 中,可能引入另一种测试缺类。若项目已有 exclusion、自定义 configuration 或插件统一修改依赖,修正这一行后仍要检查最终依赖图。
对于标准 Boot 构建,provided 依赖会进入可执行 WAR 的 WEB-INF/lib-provided。这种打包方式兼顾外部容器部署与 java -jar 运行,不能用“测试能跑”代替 WAR 部署验证。
修改后重新检查 testRuntimeClasspath,再运行原来失败的测试,并验证 WAR 在目标容器里的启动。验收要看到对应 Web 类可以加载、测试真正执行,以及容器没有因重复打包或缺失依赖而失败。保留原构建文件;出现新的容器兼容问题时按具体版本处理,不通过单独锁定任意 Spring Framework JAR 来绕开 Boot 的依赖管理。


