SpringBoot读取Jar包中静态资源原理

原理

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/"目录文件。

相关

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

友情链接更多精彩内容