默認情況下,SpringBoot從clsspath下的/META-INF/resources/,/resources/,/static/, /public/或ServletContext根路徑下查找靜態(tài)資源,默認配置變量為ResourceProperties.CLASSPATH_RESOURCE_LOCATIONS。這是通過Spring MVC的ResourceHttpRequestHandler實現(xiàn)的,也可以自定義WebMvcConfigurerAdapter子類覆寫addResourceHandlers方法來改變資源映射行為。
靜態(tài)資源基本配置
spring:
resources:
static-locations: classpath:/resources/,classpath:/html/
mvc:
static-path-pattern: /res/** #靜態(tài)資源映射路徑
經(jīng)過上面配置后,頁面請求的每個靜態(tài)文件必須包含/res/,這樣靜態(tài)文件才能映射到static-locations路徑,沒有配置就使用默認的。規(guī)范所有靜態(tài)資源統(tǒng)一前綴,在使用shiro等攔截工具時,可以匹配/res/** 不進行權(quán)限檢查。
資源緩存配置
spring:
resources:
cache:
period: #間隔周期,默認秒
cachecontrol: #緩存控制
max-age: #緩存最長時間,默認秒
no-cache: true #通過服務器驗證后才能重用響應的緩存
no-store: true #關(guān)閉緩存
資源緩存一般用于緩存應用靜態(tài)資源和webjars下面的資源,默認情況下,springboot會配置/webjars/**對應classpath:/META-INF/resources/webjars/的資源映射并進行緩存配置,static-path-pattern也會對應static-locations進行緩存配置。
靜態(tài)資源訪問策略,基于VersionResourceResolver實現(xiàn)
resources:
chain:
gzipped: true #響應是否進行Gzip壓縮處理
strategy:
content: #文件內(nèi)容MD5 hash
enabled: true #是否啟用
paths:
fixed: #固定版本
enabled: true #是否啟用
version:
paths:
- 文件內(nèi)容MD5
如index.css 文件內(nèi)容當前MD5值是e36d2e05253c6c7085a91522ce43a0b4,后來修改了該文件,產(chǎn)生了新的MD5值g47d2e05253c6c7085a91522ce43a0b4,頁面css地址之前是index-e36d2e05253c6c7085a91522ce43a0b4.css,現(xiàn)在必須改成index-g47d2e05253c6c7085a91522ce43a0b4.css才能正確訪問該文件,一般這種全局路徑前綴,必須在一個地方定義,其他乙方引入,如在freemarker中用全局變量代替,便于全局更改。
//默認使用FileNameVersionPathStrategy,如path/foo-{version}.css
public String getResourceVersion(Resource resource) {
try {
byte[] content = FileCopyUtils.copyToByteArray(resource.getInputStream());
return DigestUtils.md5DigestAsHex(content);
}
catch (IOException ex) {
throw new IllegalStateException("Failed to calculate hash for " + resource, ex);
}
}
- 固定版本號
如:{version}/js/main.js,這個version可以自定義,原理同上。