【问题标题】:Set setCachePeriod for static resources in spring boot在spring boot中为静态资源设置setCachePeriod
【发布时间】:2016-08-18 12:57:30
【问题描述】:

我使用的是spring boot,/static作为js和css等静态资源,目前还不错,而我想设置这些文件的缓存头,所以我尝试了这个:

@Configuration
public class BaseMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/").setCachePeriod(24 * 3600 * 365); 
    }
}

但是在那之后,应用程序无法从/static 文件夹中提供任何内容。

有什么问题?

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    在我看来,最好使用spring.resources.cache-period属性来设置默认Boot的缓存周期Resource Handler。因此,将以下内容添加到您的application.properties

    spring.resources.cache-period = 31536000
    

    并删除BaseMvcConfig 配置文件。

    【讨论】:

    • 使用Spring默认配置,如果你将文件保存在classpath:/static/all.css,你可以通过http://localhost:8080/all.css访问它。如果您正在使用该 Java 配置,您应该将您的请求发送到 http://localhost:8080/static/all.css
    • spring.resources.cache-period 已弃用,取而代之的是 spring.resources.cache.period
    • spring.resources.cache.cachecontrol.max-age 为我工作
    • spring.resources.cache-periodspring.resources.cache.period 已弃用。你应该使用:spring.web.resources.cache.period
    【解决方案2】:

    由于spring.resources.cache-period 已被弃用,您可能希望改用较新的spring.web.resources.cache.period,这需要几秒钟(如前)或Duration 规范,如下所示:

    spring.web.resources.cache.period = P30D
    

    请参阅Duration#parse()JavaDoc 以供参考。

    【讨论】:

    • spring.resources.cache.period 已弃用。现在你应该使用:spring.web.resources.cache.period
    • 有趣的是,我的 更新帖子 本身就已经过时了。但是,我会很高兴地更新我的更新帖子。 :-)
    【解决方案3】:

    如果您想为控制器使用 Spring Security 并为静态内容设置缓存,那么您可能需要在 WebSecurityConfigurerAdapter 中配置异常并在 application.properties 中设置缓存周期:

    @Override 
    public void configure(WebSecurity web) throws Exception { 
       web.ignoring().antMatchers("/js/**", "/css/**");
    } 
    
    #1 week cache
    spring.resources.cache-period = 604800
    

    【讨论】:

      猜你喜欢
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      相关资源
      最近更新 更多