美文网首页
SpringBoot读取Jar包中静态资源原理

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

作者: LazzMan | 来源:发表于2020-07-21 23:56 被阅读0次

    原理

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

    相关

    相关文章

      网友评论

          本文标题:SpringBoot读取Jar包中静态资源原理

          本文链接:https://www.haomeiwen.com/subject/gnngkktx.html