源码展示
WebMvcAutoConfiguration.java源码中找到addResourceHandlers方法
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//this.resourceProperties.isAddMappings()如果对resourceProperties进行配置,那么就会禁用默认资源处理
//resourceProperties.isAddMappings() 默认为true
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
//获取缓存配置的资源处理程序提供的资源缓存周期。
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
//getCache().getCachecontrol()缓存控制HTTP头配置
//以下一段是将classpath:/META-INF/resources/webjars/映射为/webjars/**
//只要存在/META-INF/resources/webjars/都可以通过/webjars/**进行访问
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[] staticLocations ={ "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/" }
//以下这段代码可以通过"/**"访问staticLocations包含 的路径下去找资源
//资源访问存在优先级
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
在Springboot,我们可以使用以下方式处理静态资源
webjars目录的访问地址:
locatlhost:8080/wabjars/**
META-INF/resources/ ,public ,static , /** ,resources 的目录访问地址
localhost:8080/
访问优先级
通过源码,我们发现staticLocations 存在的路径中都会映射为"/**",当其他存在相同文件时,则会按照以下的顺序进行进行访问
- META-INF/resources/
- resources
- static(默认)
- public
还有webjars的加载方式请看这篇博文springboot使用webjars加载资源
如有不足之处,请指出,谢谢!
每天进步一点点。