SpringBoot源码分析——静态资源访问路径
玩过SpringBoot的朋友都知道,新建SpringBoot项目,静态资源可以手动放在{resource/public/, resources/resources/, resource/static/}三个路径下
亦或者是采用Maven方式导入静态资源
也可在application.yml/application.properties文件中使用
spring.resources.static-locations=自定义的路径
自定义路径,但自定义路径后这些路径将失效。
我对此很好奇,因此去看了springboot源码寻求为什么。
我们找到WebMvcAutoConfiguration.java文件
图片中标红框位置 ResourcePreperties 就是存放静态资源的类
可以看到 staticLocations 初始化的之就是{ "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }
classpath:/META-INF/resources/:就是采用Maven方式导入静态资源文件时springboot默认读取路径
classpath:/resources/:/resources/resources/
classpath:/static/", "classpath:/public/:/resources/static/
现在我们找找springboot是怎么来找静态资源文件的,在WebMvcAutoConfiguration.java文件中我们可以看到
解读:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//如果不是默认设置,将直接返回,也就是只采取了自定义设置
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
//设置默认的webjars方式的静态资源路径
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));
}
//设置手动导入的静态资源路径
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
小知识:
我们通常将静态资源放置在{resource/public/, resources/resources/, resource/static/}路径下经实测,
这三个路径的优先级为:
resources/resources/ > resource/static/ > resource/public/