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

Spring中ResponseEntity返回双Cache-Control响应头的原因排查

Spring ResponseEntity出现重复Cache-Control头的原因与解决办法

原因

你遇到的两个Cache-Control头问题,大多是因为Spring Security或Spring MVC的默认配置自动添加了Cache-Control: private,而你手动设置的max-age=600, public是额外追加的,两者叠加导致响应头重复。

具体来说:

  • Spring Security默认会为所有HTTP响应添加Cache-Control: private等缓存控制头,目的是防止敏感数据被公共缓存(比如CDN、代理服务器)存储。
  • 部分Spring MVC的默认配置也会自动注入基础缓存头,和你手动设置的内容形成冲突。

解决办法

1. 关闭Spring Security的默认缓存控制

如果项目用了Spring Security,直接在安全配置类里禁用默认的缓存头设置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 保留你的其他安全配置
            .headers(headers -> headers.cacheControl(cache -> cache.disable()));
    }
}

2. 统一覆盖缓存头

如果不想完全禁用默认配置,可以通过拦截器直接覆盖响应头,确保最终只有你需要的Cache-Control值:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                response.setHeader("Cache-Control", "max-age=600, public");
            }
        });
    }
}

这种方式会在所有请求处理完成后,强制设置你需要的缓存头,覆盖任何之前添加的同类头。

3. 排查自定义组件

检查项目中有没有自定义的拦截器、过滤器,或者第三方依赖(比如监控、日志组件)在偷偷添加Cache-Control头,这类组件可能会在你的代码之后修改响应,导致重复。

验证方式

可以临时注释掉Spring Security的相关配置,再请求接口,看响应头是否只剩你设置的Cache-Control,以此确认问题来源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:01:28