You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Boot 2迁移至3后RestTemplateBuilder禁用Cookie管理的适配问题

Spring Boot 2迁移至3后RestTemplateBuilder禁用Cookie管理的适配问题

嗨,我来帮你搞定这个Spring Boot版本迁移时碰到的RestTemplate Cookie管理适配问题~

你遇到的问题本质是Spring Boot 3升级了依赖的Apache HttpClient版本,导致HttpClientBuilder.build()的返回类型从原来的HttpClient变成了CloseableHttpClient,而HttpComponentsClientHttpRequestFactory的构造器预期接收HttpClient接口类型。不过别慌,CloseableHttpClient本身就是HttpClient的子类,类型上是完全兼容的,只需要稍微调整下代码写法就能解决。

给你两种可行的解决方案:

方案一:直接使用(推荐)

因为子类实例可以直接赋值给父类接口变量,编译时会自动完成向上转型,所以你的代码其实只需要保留原有逻辑就能正常运行,不需要额外修改:

public static RestTemplateBuilder getRestTemplateBuilder() {
    return new RestTemplateBuilder()
            .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(
                    HttpClientBuilder
                            .create()
                            .disableCookieManagement()
                            .build()));
}

方案二:显式强转(解决编译推断问题)

如果你的IDE或者编译器因为类型推断出现报错,可以显式将CloseableHttpClient强转为HttpClient

public static RestTemplateBuilder getRestTemplateBuilder() {
    return new RestTemplateBuilder()
            .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(
                    (HttpClient) HttpClientBuilder
                            .create()
                            .disableCookieManagement()
                            .build()));
}

另外补充一句,CloseableHttpClient实现了Closeable接口,如果你需要更严谨地管理资源,后续可以考虑在合适的时机调用close()方法,但在Spring环境下,RestTemplate通常会帮你处理好资源的生命周期,一般不需要额外操心。

备注:内容来源于stack exchange,提问作者springbooter99

火山引擎 最新活动