Springboot加载静态资源
静态资源映射路径:
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
源码分析:
- 找到springboot加载静态资源的自动配置组件类 WebMvcAutoConfiguration,该类中有个加载静态资源的方法:
@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);
}
});
}
- 重点来看这行代码:读取默认的静态资源配置路径
registration.addResourceLocations(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/" };
- 加载静态资源的优先级:
通过在以上的资源目录下分别放置一个同名静态资源(内容不同)来测试加载的优先级
得出优先级顺序就是数组存放的先后顺序,即:从上到下,优先级逐减
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/