先找到这个类:WebMvcAutoConfiguration,在这个jar包里面,还是自动配置
WebMvcAutoConfiguration中有一个 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});
}
});
}
}
先看这个:
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
}
如果isAddMappings为false,就打印默认资源映射路径失效了。isAddMappings方法其实就是返回一个addMappings变量(在WebProperties中)
addMappings的含义就是运行访问静态资源,如果你设置成false,就是禁用所有静态资源映射。
站长在写这篇教程的时候,用的SpringBoot版本为2.5.1,是目前最新的版本。发现和之前的版本比起来,改动还是很大的。翻源码很麻烦,我就直接告诉你结论就行了。
默认的静态资源目录是:
new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
这点和以前是一样的,测试一下
image
访问什么路径能返回public.js呢?
在WebMvcProperties中,有一个staticPathPattern属性。
image
默认就是/**,所以,无论你访问什么,都可以被静态资源处理器接受。
启动项目,访问http://localhost:8888/public.js
[图片上传失败...(image-1fcffe-1625294071735)]
成功访问,现在我们手动添加一个静态目录。
spring:
profiles: test
resources:
static-locations: [classpath:/my/]
[图片上传失败...(image-822516-1625294071735)]
访问http://localhost:8888/my.txt,也成功了。
最后,把静态资源开关关掉。
spring:
profiles: test
resources:
static-locations: [classpath:/my/]
add-mappings: false
这样就访问不到任何静态资源了,不过一般来说不用关。