默認靜態資源路徑及優先級
SpringBoot對於各組件的自動配置一般都是在spring-boot-autoconfigure包中,
重點查看一下兩類文件:
- ***AutoConfiguration
- ***Properties
因此直接查看Web相關包,可以看到org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration有addResourceHandlers方法:
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();
// 如果容器中有的話,加載classpath下/webjars/**
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
// 獲取靜態資源默認映射路徑,默認爲/**
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
// 加載默認靜態資源
registry.addResourceHandler(staticPathPattern)
// 默認靜態資源
.addResourceLocations(getResourceLocations(
this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
}
org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
@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/" };
/**
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
//......
//獲取靜態資源默認路徑
static String[] getResourceLocations(String[] staticLocations) {
String[] locations = new String[staticLocations.length
+ SERVLET_LOCATIONS.length];
System.arraycopy(staticLocations, 0, locations, 0, staticLocations.length);
System.arraycopy(SERVLET_LOCATIONS, 0, locations, staticLocations.length,
SERVLET_LOCATIONS.length);
return locations;
}
由此可以知道SpringBoot中,默認靜態資源的訪問路徑爲:
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
此默認路徑優先級由高到低。
自定義資源路徑以及映射
# 不會覆蓋默認靜態資源路徑
spring:
resources:
static-locations: classpath:/mystatic/,classpath:/otherstatic/
# 只有在訪問路徑中有該路徑時方可訪問靜態資源,如果設置了servlet-context,那麼也需要在路徑中加入。
mvc:
static-path-pattern: /mystatic