I am using spring boot, and the /static is served as static resources like js and css, so far so good, while I want to set the cache header of these files, so I tried this:
@Configuration
public class BaseMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/").setCachePeriod(24 * 3600 * 365);
}
}
However after that, the application can not serve anything from the /static folder.
What's the problem?
In my opinion, it's better to use spring.resources.cache-period property to set the cache period of default Boot Resource Handler. So add the following to your application.properties:
spring.resources.cache-period = 31536000
And delete the BaseMvcConfig config file.
Since spring.resources.cache-period is deprecated, you may want to use the newer spring.web.resources.cache.period instead, which takes either seconds (as before), or a Duration specification like this:
spring.web.resources.cache.period = P30D
See Duration#parse() JavaDoc for reference.
If you want to use spring security for controllers and setup cache for static content then you might want to configure exceptions in your WebSecurityConfigurerAdapter and set cache period in application.properties:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**");
}
#1 week cache
spring.resources.cache-period = 604800
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With