Springboot2 thymeleaf 静态资源加版本号控制
2020-08-06 本文已影响0人
VIAE
最近写了一个前后端不分离的项目了,用的Springboot2 thymeleaf
用的js原生,没有用到webpack,所以不能在每次js变更以后打包自动给静态文件加上hash后缀
关于静态资源缓存不更新的问题,用了以下几种解决方案
方法一
在静态资源引用的时候加上版本号,最开始我就是这么做的,因为当时确实没几个文件
index.html
<link rel="stylesheet" type="text/css" href="../static/css/index.css?v=1.0.0">
<script type="text/javascript" src="../static/js/index.js?v=1.0.0"></script>
bug:文件多了以后,这种方法就不太适合了
方法二
动态添加静态资源,加时间戳
index.html
<script>
document.write('<script type="text/javascript" src="../static/js/index.js?v=' +new Date().getTime()+'"></script>')
</script>
bug:每次刷新页面时间戳都会改变,都要重新拉取资源
方法三
Springboot静态资源路径映射 添加版本号
首先更改java配置
WebMvcConfig
@Configuration
public class MvcInterceptorConfig implements WebMvcConfigurer {
/**
* 添加静态资源文件
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
.resourceChain(false)
.addResolver(new VersionResourceResolver()
.addFixedVersionStrategy("v1.0.1", "/**") //添加版本号,手动修改版本号
// .addContentVersionStrategy("/**") //md5码方式
);
}
}
其次修改
application.properties (版本号与md5配置一样,否则不生效)
spring.resources.chain.strategy.content.enable=true
spring.resource.chain.strategy.content.path=/**
使用
index.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<link rel="stylesheet" type="text/css" th:href="@{/static/css/index.css}">
<script type="text/javascript" th:src="@{/static/js/index.js}"></script>
</head>
</html>
最终解析路径:localhost:8080/static/v1.0.1/js/index.js
方法四
只修改application.properties 配置版本号
# 指定版本号
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/**
spring.resources.chain.strategy.fixed.version=v1.0.0
最终解析路径:localhost:8080/v1.0.1/js/index.js
参考文档 https://blog.csdn.net/xichenguan/article/details/52794862