想要了解springboot处理哪些静态资源。我们需要到底层去看源码,这样才能知道怎么配置。
首先我们需要找到WebMvcAutoConfiguration这个类,这是专门配置SpringMvcde。
在这个类里面,找到静态资源相关的方法addResourceHandlers。
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
this.addResourceHandler(registry, "/webjars/**", "classpath:/meta-INF/resources/webjars/");
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
registration.addResourceLocations(new Resource[]{resource});
}
});
}
}
我们可以看到"/webjars/**", "classpath:/meta-INF/resources/webjars/"这个目录下的所有静态资源都可以被访问到,当然这是不常用的。
第二种getStaticLocations(),点进去看一下
public String[] getStaticLocations() {
return this.staticLocations;
}
返回的staticLocations再点进去
this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
CLASSPATH_RESOURCE_LOCATIONS;就是静态资源存放的路径,点进去查看
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/meta-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
classpath对应的目录结构是resouces。所以这几个包下面的静态资源都能被访问



