1

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 );
    }
}
Community
  • 1
  • 1
xenoterracide
  • 16,274
  • 24
  • 118
  • 243

1 Answers1

2

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
Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • hey thanks, what happens if I set the `cache-period` and configure this? say I want a sane default for most statics but something different for webjars? basically I haven't cache busted my own static resources yet, but the web jars are by virtue of having versions listed in them. – xenoterracide Jul 17 '16 at 20:42
  • If you configure both, web jars resources will have the cache period configured by your adapter. All other static resources will have the cache period configured in application.properties. – Andy Wilkinson Jul 18 '16 at 07:13
  • turns out I have to do `.setCacheControl( CacheControl.maxAge( 30, TimeUnit.DAYS ).cachePublic() );` without public cloudfront is opting to not cache (though not sure why it has decided it's ok to cache my non static controller response... I don't suppose there's a magic properties setting for 'public'? ` – xenoterracide Jul 18 '16 at 13:07
  • There isn't. The properties are only for what's available on `ResourceHandlerRegistration` directly – Andy Wilkinson Jul 18 '16 at 15:25
  • The new Spring Boot config property is now `spring.web.resources.cache.period = 1d` – rieckpil Jun 28 '22 at 09:52