其他分享
首页 > 其他分享> > springboot读取静态文件路径顺序

springboot读取静态文件路径顺序

作者:互联网

springboot读取静态文件路径顺序

源码

–》WebMvcAutoConfiguration
–》addResourceHandlers

在这里插入图片描述

@Override
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();
    // 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));
    }
}

顺序:判断是否有自义定路径,有的话默认路径失效。

先自定义—>其次是webjars/**–>最后是默认路径如下图

在这里插入图片描述

// 进入方法
public String[] getStaticLocations() {
    return this.staticLocations;
}
// 找到对应的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
// 找到路径
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { 
    "classpath:/META-INF/resources/",
  "classpath:/resources/", 
    "classpath:/static/", 
    "classpath:/public/" 
};

总结(默认静态文件路径顺序)

在这里插入图片描述
自定义静态资源路径

放静态资源文件的,在application.properties中配置

spring.resources.static-locations=classpath:/coding/,classpath:/kang/

标签:webjars,springboot,静态,路径,classpath,registry,resources,读取
来源: https://blog.csdn.net/kang1011/article/details/118279462