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

2020-07-21  本文已影响0人  LazzMan

原理

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

相关

上一篇下一篇

猜你喜欢

热点阅读