1.spring boot默認資源處理
Spring Boot 默認為我們提供了靜態資源處理,使用 WebMvcAutoConfiguration 中的配置各種屬性。
spring boot默認加載文件的路徑是:
/META-INF/resources/
/resources/
/static/
/public/
這些目錄下面, 當然我們也可以從spring boot源碼也可以看到Java代碼:
1
|
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/" , "classpath:/resources/" , "classpath:/static/" , "classpath:/public/" }; |
上面這幾個都是靜態資源的映射路徑,優先級順序為:META-INF/resources > resources > static > public
所有本地的靜態資源都配置在了classpath下面了, 而非在webapp下了。
如果Spring Boot提供的Sping MVC不符合要求,則可以通過一個配置類(注解有@Configuration的類)加上@EnableWebMvc注解來實現完全自己控制的MVC配置。
當然,通常情況下,Spring Boot的自動配置是符合我們大多數需求的。在你既需要保留Spring Boot提供的便利,有需要增加自己的額外的配置的時候,可以定義一個配置類并繼承WebMvcConfigurerAdapter,無需使用@EnableWebMvc注解。
如果@EnableWebMvc了,那么就會自動覆蓋了官方給出的/static, /public, META-INF/resources, /resources等存放靜態資源的目錄。
2.自定義資源映射
這里我們提到這個WebMvcConfigurerAdapter這個類,重寫這個類中的方法可以讓我們增加額外的配置,這里我們就介紹幾個常用的。
自定義資源映射addResourceHandlers
比如,我們想自定義靜態資源映射目錄的話,只需重寫addResourceHandlers方法即可。
1
2
3
4
5
6
7
8
|
@Configuration public class SimpleWebAppConfigurer extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler( "/myresource/**" ).addResourceLocations( "classpath:/myresource/" ); super .addResourceHandlers(registry); } } |
通過addResourceHandler添加映射路徑,然后通過addResourceLocations來指定路徑。
如果我們將/myresource/* 修改為 /* 與默認的相同時,則會覆蓋系統的配置,可以多次使用 addResourceLocations 添加目錄,優先級先添加的高于后添加的。
3.使用外部資源
如果我們要指定一個絕對路徑的文件夾(如 H:/images/ ),則只需要使用addResourceLocations 指定即可。
1
2
|
// 可以直接使用addResourceLocations 指定磁盤絕對路徑,同樣可以配置多個位置,注意路徑寫法需要加上file: registry.addResourceHandler( "/myimgs/**" ).addResourceLocations( "file:H:/myimgs/" ); |
通過配置文件配置,上面是使用代碼來定義靜態資源的映射,其實Spring Boot也為我們提供了可以直接在 application.properties(或.yml)中配置的方法。
配置方法如下:
1
2
3
|
# 默認值為 /** spring.mvc. static -path-pattern=classpath:/META-INF/resources/,classpath:/resources/,classpath:/ static /,classpath:/ public / spring.resources. static -locations=這里設置要指向的路徑,多個使用英文逗號隔開 |
使用 spring.resources.static-locations 可以重新定義 pattern 所指向的路徑,支持 classpath: 和 file: (上面已經做過說明)
注意 spring.mvc.static-path-pattern 只可以定義一個,目前不支持多個逗號分割的方式。
以上所述是小編給大家介紹的spring boot中的靜態資源加載處理方式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/web424/p/6755975.html