当前位置: 代码迷 >> 综合 >> SpringBoot 静态资源类
  详细解决方案

SpringBoot 静态资源类

热度:53   发布时间:2023-10-08 18:58:46.0

SpringBoot 对于SpringMVC的自动化配置都在  WebMvcAutoConfiguration类中。

WebMvcAutoConfiguration类

有个静态内部类 WebMvcAutoConfigurationAdapter 实现了

 

WebMvcConfigurer 的addResourceHandlers 用来配置静态资源过滤。

if (!registry.hasMappingForPattern(staticPathPattern)) {customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

静态资源位置定义:

@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;public String[] getStaticLocations() {return this.staticLocations;}public void setStaticLocations(String[] staticLocations) {this.staticLocations = appendSlashIfNecessary(staticLocations);}private String[] appendSlashIfNecessary(String[] staticLocations) {String[] normalized = new String[staticLocations.length];for (int i = 0; i < staticLocations.length; i++) {String location = staticLocations[i];normalized[i] = location.endsWith("/") ? location : location + "/";}return normalized;}