How does Spring Boot handle static resource caching

nikhilxd

Nikhil Soman Sahu

Posted on July 14, 2024

How does Spring Boot handle static resource caching

Well Spring Boot provides several ways to handle caching of static resources:

Default Caching Behavior

By default, Spring Boot serves static resources with a one-year future expiration to maximize browser caching and reduce HTTP requests[5]. It also supports HTTP conditional requests with Last-Modified headers based on the resource's last modified timestamp[5].

Configuring Resource Handlers

You can customize static resource handling by configuring a ResourceHandlerRegistry in a WebMvcConfigurer implementation[1][3][4]:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/")
            .setCachePeriod(3600)
            .resourceChain(true)
            .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
    }
}
Enter fullscreen mode Exit fullscreen mode

This allows you to:

  • Map URLs to resources
  • Set cache periods for resources
  • Enable resource versioning to ensure browsers always get the latest version

Configuring Cache Control Headers

You can also set Cache-Control headers directly in the HttpServletResponse from a controller method[2]:

@Controller
public class MyController {
    @RequestMapping(...)
    public String myMethod(HttpServletResponse response) {
        response.setHeader("Cache-Control", "max-age=14400");
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

Or by returning a ResponseEntity with the desired cache control settings[2]:

@Controller
public class MyController {
    @RequestMapping(...)
    public ResponseEntity<?> myMethod() {
        return ResponseEntity.ok()
            .cacheControl(CacheControl.maxAge(Duration.ofHours(4)))
            .body(data);
    }
}
Enter fullscreen mode Exit fullscreen mode

Disabling Caching for Static Resources

If needed, you can disable caching for specific static resource paths by configuring Spring Security to ignore them[2]:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**", "/js/**");
    }
}
Enter fullscreen mode Exit fullscreen mode

In summary, Spring Boot makes it easy to serve and cache static web content with sensible defaults. You can further customize caching behavior by configuring resource handlers, setting cache control headers, or disabling caching for specific paths as needed.

💖 💪 🙅 🚩
nikhilxd
Nikhil Soman Sahu

Posted on July 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related