spring boot 對 web 靜態資源的配置管理是經過配置類 WebMvcAutoConfiguration
來實現的。css
顧名思義,WebMvcAutoConfiguration 是web開發的相關配置都放在該類中的。那咱們看看靜態資源是如何配置的呢?html
public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache() .getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } //staticPathPattern的值是 /** String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations( this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } }
從上面的代碼中能夠解讀出兩點關鍵信息:jquery
全部的"/webjars/**
都去classpath:/META-INF/resources/webjars/
路徑下找靜態資源web
<dependency> <groupId>org.webjars.bower</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
若是路徑是/**
時,就去如下spring
classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public/
類路徑查找資源文件,idea 中的項目路徑以下圖所示:
那咱們如何訪問靜態資源呢?經過下面的url可直接訪問bootstrap
http://localhost:8080/asserts/css/bootstrap.min.css
可是注意,假如你把靜態資源存放在classpath:/static/
,試圖經過http://localhost:8080/static/asserts/css/bootstrap.min.css
來訪問靜態資源是訪問不到的。mvc
3.歡迎頁面的映射app
private Resource getIndexHtml(String location) { return this.resourceLoader.getResource(location + "index.html"); }
意思是隻要在咱們的靜態資源文件夾中放有 index.html文件,就能自動訪問到,好比:http://localhost:8080,靜態文件目錄指的是 2 中提到的目錄。框架
咱們的資源文件路徑屬性是有ResourceProperties
中定義的。ide
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS; }
因此自定路徑只須要覆蓋 staticLocations 的默認路徑便可,在 application.properties 文件中設置該路徑
spring.resources.static-locations=classpath:/hello,classpath:/test #能夠設置多個路徑