學習 Spring Boot 配置靜态資源。
1 Spring MVC 配置靜态資源
先來回顧下在 Spring MVC 中如何配置靜态資源。使用 Spring MVC 時,靜态資源會被攔截,需要添加額外的配置,一般在
spring-mvc.xml
中配置,如下:
<mvc:resources mapping="/favicon.ico" location="favicon.ico" />
<mvc:resources mapping="/static/**" location="/static/" />
2 Spring Boot 配置靜态資源
2.1 預設位置
Spring Boot 項目中的靜态資源最常見的位置在
src/main/resources/static
目錄下,其實共有 5 個預設位置能放,重複的資源以優先級高的為準。如下(優先級: 1 > 2 > 3 > 4 > 5 ):
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
- /
其中,/ 表示類似 webapp 目錄,即 webapp 中的靜态檔案也可以直接通路。
如果在
src/main/resources/static
目錄下有一個 1.png 的檔案,那麼通路路徑是
http://127.0.0.1:8080/1.png
,不需要加 static 。類似 Spring MVC 中的配置
<mvc:resources mapping="/**" location="/static/"/>
,實際上系統會去 /static/1.png 目錄下查找相關的檔案。
2.2 源碼解讀
打開
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
,找到了靜态資源攔截的配置,如下:
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(
registry.addResourceHandler(new String[]{staticPathPattern})
.addResourceLocations(
WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())
)
.setCachePeriod(this.getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
-
傳回 “/**” 。this.mvcProperties.getStaticPathPattern()
-
傳回 4 個位置 “classpath:/META-INF/resources/”, “classpath:/resources/”, “classpath:/static/”, “classpath:/public/” ,然後this.resourceProperties.getStaticLocations()
又添加了 “/” ,這樣總共就是上述 5 個位置。WebMvcAutoConfiguration.getResourceLocations
2.3 自定義位置
上述 5 個是系統預設的位置,有 2 種辦法可以實作自定義位置。
- 通過
配置檔案。application.properties
# 自定義配置靜态資源的比對規則和路徑
# 定義請求 URL 規則
# spring.mvc.static-path-pattern=/**
# 定義資源位置
# spring.resources.static-locations=classpath:/cxy35/
- 通過 Java 代碼。
新增配置類
WebMvcConfig
, 如下:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// 自定義配置靜态資源的比對規則和路徑
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/cxy35/");
}
}
- Spring Boot 教程合集(微信左下方閱讀全文可直達)。
- Spring Boot 教程合集示例代碼:https://github.com/cxy35/spring-boot-samples
- 本文示例代碼:https://github.com/cxy35/spring-boot-samples/tree/master/spring-boot-web/spring-boot-staticresources
掃碼關注微信公衆号 程式員35 ,擷取最新技術幹貨,暢聊 #程式員的35,35的程式員# 。獨立站點:https://cxy35.com