原理
SpringBoot本身注入了一个 Bean org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter
,其中的addResourceHandlers
方法添加了资源路径映射。
源码:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
等价于下面代码:
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/")
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/")
也就是说,只要在jar包中的"classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/"
下放入静态资源,就可以正常访问
也就可以推断出,SpringBoot会读取所有Jar包下"classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/"
目录文件。
相关
- 参考swagger-bootstrap-ui的实现
- 参考springfox-swagger-ui配合springfox-boot-starter中的
SwaggerUiWebMvcConfigurer
类实现自定义的资源路径映射
网友评论