Search code examples
springhttpspring-mvcspring-bootcache-control

How do I configure cache-control for webjars in spring boot


I've seen a couple of existing answers but when I add the following all webjars start returning 404s. How can I configure cache control for all of my webjars?

@Configuration
public class HttpCacheControlConfig extends WebMvcConfigurerAdapter {


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**").setCachePeriod( 3600 * 24 );
    }
}

Solution

  • You haven't configured any resource locations for the handler. You need something like this:

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/")
            .setCachePeriod(3600 * 24);
    

    Alternatively, if you're happy for all of your static resources to have the same cache period then you don't need a WebMvcConfigurerAdapter as you can just configure it with a property in application.properties:

    spring.resources.cache-period = 86400