【Web开发】Spring MVC 中的静态资源与缓存

260 阅读1分钟

前言

不太建议在Java应用程序中去提供静态资源的服务,去设置那些缓存。因为我们往往会有更合适的技术来处理这些问题。比如可以用Nginx来做一个静态资源的代理。一般在系统中也会有像CMS这样的系统专门处理这样一些资源,做这些资源的变更。

Spring Boot 中的静态资源配置

  • 核⼼逻辑

    • WebMvcConfigurer.addResourceHandlers()
  • 常⽤配置

    • spring.mvc.static-path-pattern=/**
    • spring.resources.static-locations=classpath:/META-INF/ resources/,classpath:/resources/,classpath:/static/,classpath:/public/

WebMvcAutoConfigurationAdapter#addResourceHandlers。WebMvcAutoConfigurationAdapter实现了WebMvcConfigurer接口。

this.resourceProperties对应的Resources类。

Spring Boot 中的缓存配置

  • 核心逻辑

    • ResourceProperties.Cache
  • 常⽤配置(默认时间单位都是秒)

    • spring.resources.cache.cachecontrol.max-age=时间
    • spring.resources.cache.cachecontrol.no-cache=true/false
    • spring.resources.cache.cachecontrol.s-max-age=时间

Controller 中⼿⼯设置缓存

建议的资源访问⽅式