Spring boot學習 (九) 之靜態資源的學習
前言
在上一篇學攔截器的時候我們自定義配置類的時候有實現一個非常重要的介面 : WebMvcConfigurer
,這次我們繼續用這個類來學習 spring-boot
的靜態資源處理。 Spring-boot
預設提供了靜態資源處理,使用 WebMvcAutoConfiguration
配置各種屬性。沒有特殊的要求建議大家使用預設配置。
正文
一,預設的資源對映
spring-boot預設配置的資源對映有下面幾種:
-
/META-INF/resources
-
/resources
-
/static
-
/public
他們都在classpath:
目錄下,如/static在工程中的目錄為src/main/resources/static
。預設配置的/**
對映到/static
(或/public、/resources、/META-INF/resources
),
目錄這麼多那麼他們的優先順序順序是怎麼樣的呢?大家可以像我一樣在不同的目錄下面放同一個index.html
,html
檔案裡面的內容不同:

會發現優先順序最高的是: /META-INF/resources
。經測試他們的優先順序順序為:
META/resources > resources > static > public
二,自定義資源對映
上面介紹的是幾種的是spring-boot預設的資源對映,在一般的情況下我們就使用預設的配置即可。當然我們也是可以自定義資源對映的,下面介紹幾種不同情況的自定義方式。
1,自定義目錄(這裡用到了 WebMvcConfigurer
介面)
實現 WebMvcConfigurer
介面,並重寫 addResourceHandlers
方法,在裡面自定目錄,程式碼如下:
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/mlin/**").addResourceLocations("classpath:/mlin/"); } }
訪問 mlin
資料夾中的 index.html
圖片的地址為 http://localhost:8080/mlin/index.html
如果將 /mlin/**
改成 /**
就表示覆蓋系統的預設配置,當訪問: http://localhost:8080/index.html 會訪問到 classpath:/mlin/
下面的資源而不是原先的 /META-INF/resources
下面的資源了。
可以多次使用 addResourceLocations
新增目錄,優先順序先新增的高於後新增的。
registry.addResourceHandler("/**").addResourceLocations("classpath:/mlin/").addResourceLocations("classpath:/static/");
還可以寫成:
registry.addResourceHandler("/**").addResourceLocations("classpath:/mlin1/", "classpath:/mlin2/", "classpath:/mlin3/");
注:自定義目錄對映,不影響Spring Boot的預設對映。
2,使用外部目錄
使用外部目錄很簡單,只要在路徑記得加 file:
,再指定絕對路徑即可:
registry.addResourceHandler("/mlin/**").addResourceLocations("file:C:/test/");
3,通過配置檔案配置
spring-boot
也為我們提供了可以直接在 application.properties(或.yml)
中配置的方法:
# 預設值為 /** spring.mvc.static-path-pattern= # 預設值為 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ spring.resources.static-locations=
- 當
spring.mvc.static-path-pattern=/mlin/**
而spring.resources.static-locations=
表示:
想訪問classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
下面的資源index.html
時,訪問路徑為: http://localhost:8080/mlin/index.html ,而不是之前的 http://localhost:8080/index.html - 當
spring.mvc.static-path-pattern=/mlin/**
而spring.resources.static-locations=/mlin/
表示:
訪問路徑為: http://localhost:8080/mlin/index.html 和訪問路徑為: http://localhost:8080/index.html 訪問的都是classpath:/mlin/
下面的index.html
原創作者:夢凌小樣
作品連結: https://www.jianshu.com/p/84f66aa9b17d 【原創不易,轉載請註明出處,感謝理解】
一位愛生活,愛創作,愛分享,愛自己的90後女程式員一枚,記錄工作中的點點滴滴,一起學習,共同進步,期待能和優秀的您交上朋友