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

Spring Boot 2不使用Spring Security时缓存响应头配置不生效问题

解决Spring Boot 2 API响应中Cache-Control头不完整的问题

Hey there, let's break down why only the max-age header is showing up in your Chrome DevTools, while the other Cache-Control settings you configured are missing.

核心原因:配置项用错了场景!

The spring.resources.cache.cachecontrol.* properties you set in application.properties are exclusively designed for static resources (like CSS, JS, images, or other static assets served by Spring Boot). These settings don't apply to your API endpoints that return ResponseEntity<Long> — those are handled by your controller methods, not the static resource handler. That's why only max-age (which might be picked up by default in some edge cases) is visible, and the rest are nowhere to be seen.

解决方案:手动为API响应配置Cache-Control头

Here are two straightforward ways to get all your desired Cache-Control headers into your API responses:

1. 直接在控制器方法中设置响应头

You can build the HttpHeaders object manually when returning your ResponseEntity:

@GetMapping("/your-api-endpoint")
public ResponseEntity<Long> getYourValue() {
    // 创建响应头并配置缓存规则
    HttpHeaders headers = new HttpHeaders();
    CacheControl cacheControl = CacheControl.noStore()
            .mustRevalidate()
            .noCache()
            .maxAge(Duration.ZERO);
    headers.setCacheControl(cacheControl);

    // 返回带自定义头的响应
    return new ResponseEntity<>(123L, headers, HttpStatus.OK);
}

2. 用拦截器统一处理所有API的缓存头

If you want to apply these cache rules to multiple API endpoints without repeating code, use a Spring MVC interceptor:

首先,创建拦截器类:

public class ApiCacheControlInterceptor implements HandlerInterceptor {
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, 
                          Object handler, ModelAndView modelAndView) throws Exception {
        // 定义缓存控制规则
        CacheControl cacheControl = CacheControl.noStore()
                .mustRevalidate()
                .noCache()
                .maxAge(Duration.ZERO);
        
        // 将规则添加到响应头中
        response.setHeader(HttpHeaders.CACHE_CONTROL, cacheControl.getHeaderValue());
    }
}

然后在Web配置类中注册拦截器:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ApiCacheControlInterceptor())
                .addPathPatterns("/api/**"); // 匹配你的API路径规则
    }
}

验证小技巧

To avoid browser cache interference when checking headers, use curl to test the response directly:

curl -I http://your-app-base-url/your-api-endpoint

This will print all response headers immediately, so you can confirm all your Cache-Control directives are present.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:23:22