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

Spring Boot 3配置TestRestTemplate后遇ClassNotFoundException求助

问题解决:Spring Boot3中TestRestTemplate PATCH请求依赖冲突导致ClassNotFoundException

问题根源

Spring Boot 3 默认依赖Apache HttpClient 5版本,其类路径为org.apache.hc.client5.http.classic.HttpClient;而你引入的是旧版org.apache.httpcomponents:httpclient:4.5.14(HttpClient4),它的类路径是org.apache.http.client.HttpClient。两者包结构不兼容,导致运行时找不到对应类——即使IDE能识别(IDE可能同时加载了新旧版本的类),但实际运行时classpath里的依赖不匹配。

解决方案

1. 替换为HttpClient5依赖

修改Gradle依赖配置,移除旧版HttpClient4,引入HttpClient5:

// 移除旧依赖
// implementation 'org.apache.httpcomponents:httpclient:4.5.14'
// 引入HttpClient5(Spring Boot3已适配版本,无需指定具体版本号)
implementation 'org.apache.httpcomponents.client5:httpclient5'

2. 调整TestRestTemplate配置适配HttpClient5

如果之前的配置基于HttpClient4,需要调整为HttpClient5的API:

import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

// 配置支持PATCH请求的TestRestTemplate
HttpClient httpClient = HttpClientBuilder.create().build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
TestRestTemplate testRestTemplate = new TestRestTemplate(requestFactory);

3. 强制更新依赖并重新构建

执行以下Gradle命令,清理缓存并强制刷新依赖:

./gradlew clean build --refresh-dependencies

4. 排查依赖冲突(可选)

如果仍有问题,查看项目依赖树,确认没有同时存在HttpClient4和HttpClient5的依赖:

./gradlew dependencies

若发现冲突,用exclude排除多余依赖:

implementation('存在冲突的依赖包') {
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 11:15:53