Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring MVC versioned static assets: cache immutable bytes by content

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A content-versioned asset URL can carry a long cache lifetime because a byte change yields a different URL; HTML and private API responses need separate policies.

Version the address, not the clock

A deployed stylesheet may keep its old bytes in a browser for months. If its URL contains a content-derived version, a changed build produces a different address and can use a long public cache lifetime. A plain /assets/site.css URL cannot safely promise that lifetime across deployments. Tenant data] must not inherit this static-asset policy.

Generate URLs through the resolver

Configure a resource handler with a VersionResourceResolver, then generate links through ResourceUrlProvider or a view integration that applies the resource chain. Merely configuring the resolver does not rewrite hard-coded page URLs. If precompressed variants are served, resolver ordering matters: version the original bytes consistently. Keep HTML relatively fresh so it can point at the newly versioned asset.

Test two builds

Build with one stylesheet, capture its generated URL and response headers, then change one byte and build again. The new URL should differ, both versions should return the expected content while deployed, and the HTML should reference the current version. A CDN that purges old assets before old HTML expires can still break users.

Implementation contract

Java
@Configuration
class AssetDelivery implements WebMvcConfigurer {
    @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**")
            .addResourceLocations("classpath:/static/assets/")
            .setCacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic())
            .resourceChain(true)
            .addResolver(new VersionResourceResolver()
                .addContentVersionStrategy("/**"));
    }
}

Cost and verification

The resource chain performs version resolution and may cache lookups. Long-lived browser and CDN copies reduce repeated asset transfer, while retaining old versioned files consumes deployment storage.

Common Mistakes

  • Do not give unversioned files a one-year public lifetime.
  • Do not assume hard-coded asset links acquire a version automatically.
  • Do not apply the asset cache rule to HTML or personalized responses.

Read next

Spring MVC private Cache-Control: decide who may retain a receipt, Spring Boot layered jar: keep dependency changes out of the application layer, Spring Boot executable jar: load resources through the classpath, not a file path, Spring MVC consumes and produces: 415 and 406 are different failures, Spring MVC conditional GET: validate the representation tag.

spring
spring-web
mvc-versioned-static-asset-cache
Storage details