SpringBoot加载静态资源有关的自动配置类为WebMvcAutoConfiguration中的addResourceHandlers()方法
WebMvcAutoConfiguration的properties类为@EnableConfigurationProperties({ WebMvcProperties.class, WebProperties.class })
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
registration.addResourceLocations(resource);
}
});
}
默认配置
方式一
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
请求方式
http://localhost:8080/webjars/jquery/3.4.1/AUTHORS.txt
方式二
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
registration.addResourceLocations(resource);
}
});
this.mvcProperties.getStaticPathPattern()->private String staticPathPattern = "/**";
来自于WebMvcProperties.java
this.resourceProperties.getStaticLocations()
|
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/" };
来自于WebProperties.java
资源路径优先级
resources>static>public
上传的文件>图片>公共资源
一旦在application.yaml中定义了,那么默认配置都不会生效
spring:
mvc:
static-path-pattern: /**