springboot读取静态文件路径顺序

springboot读取静态文件路径顺序

源码

–》WebMvcAutoConfiguration
–》addResourceHandlers

springboot读取静态文件路径顺序

@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/**–>最后是默认路径如下图

springboot读取静态文件路径顺序

// 进入方法
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/" 
};

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

springboot读取静态文件路径顺序
自定义静态资源路径

  • 一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了!

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

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

上一篇:[含lw+源码等]基于Springboot+freemarker+Mysql实现的在线网盘系统[包运行成功]计算机毕业设计Java毕设


下一篇:springboot-rabbitmq