Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set setCachePeriod for static resources in spring boot

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?

like image 386
hguser Avatar asked Apr 25 '16 08:04

hguser


Video Answer


3 Answers

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.

like image 82
Ali Dehghani Avatar answered Oct 17 '22 22:10

Ali Dehghani


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.

like image 32
Michael Piefel Avatar answered Oct 17 '22 21:10

Michael Piefel


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
like image 37
Alex Cumarav Avatar answered Oct 17 '22 22:10

Alex Cumarav