springboot中如何导入静态资源

查看源码 WebMvcAutoConfiguration

public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                this.addResourceHandler(registry, this.mvcProperties.getWebjarsPathPattern(), "classpath:/META-INF/resources/webjars/");
                this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (Consumer)((registration) -> {
                    registration.addResourceLocations(this.resourceProperties.getStaticLocations());
                    if (this.servletContext != null) {
                        ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                        registration.addResourceLocations(new Resource[]{resource});
                    }

                }));
            }
        }

通过WebJars引入第三方静态资源

webJars将前端静态资源以jar包形式托管在maven仓库中,通过依赖管理直接引入项目中。springboot默认配置了/webjars/**路径映射到classpath:/META-INF/resources/webjars/目录

访问路径示例:http://localhost:8080/webjars/jquery/3.5.1/jquery.js

自定义静态资源路径

如果通过spring.mvc.static-path-pattern来自定义设置了,默认的配置就失效

或者通过配置类的形式来覆盖,比如:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/custom/**")
                .addResourceLocations("classpath:/customStatic/", "file:/externalResources/")
                .setCachePeriod(31556926); // 设置缓存时间(秒)
    }
}

默认静态资源目录

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

public String[] getStaticLocations() {
            return this.staticLocations;
}

优先级从高到低依次为:

  • classpath:/resources/
  • classpath:/static/ (默认)
  • classpath:/public/
  • classpath:/META-INF/resources/

直接通过URL根路径访问文件,例如http://localhost:8080/images/logo.png(假设文件位于static/images/logo.png

你可能感兴趣的:(springboot,spring,boot,java,前端)