SpringBoot 3.0升级RestTemplate遇相关类缺失问题求助
SpringBoot 3.0 升级后 RestTemplate 配置类找不到的解决方案
问题原因
SpringBoot 3.0 基于 Spring Framework 6.x,对应依赖的 Apache HttpClient 版本从 4.x 升级到了 5.x,原代码中使用的 4.x 版本类的包路径或类名发生了变化,导致找不到CloseableHttpClient和NoopHostnameVerifier。
解决步骤
1. 引入正确的 HttpClient 5 依赖
如果使用 Maven,在pom.xml中替换原有 httpclient 依赖(或新增):
<dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> </dependency>
如果使用 Gradle,在build.gradle中添加:
implementation 'org.apache.httpcomponents.client5:httpclient5'
2. 修改 RestTemplate 配置代码
调整类的导入路径,适配 HttpClient 5.x 的 API:
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); CloseableHttpClient httpClient = HttpClientBuilder.create() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .build(); HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); restTemplate.setRequestFactory(clientHttpRequestFactory); return restTemplate; } }
注意事项
NoopHostnameVerifier会跳过 SSL 主机名验证,仅建议在测试环境使用,生产环境请使用安全的主机名验证逻辑,比如DefaultHostnameVerifier。- Spring Framework 6.x 中的
HttpComponentsClientHttpRequestFactory已适配 HttpClient 5.x,依赖正确即可直接使用。
内容的提问来源于stack exchange,提问作者srinivasa rao marasu
相关产品推荐
相关产品推荐

