SpringBoot静态资源源码解析
2021/12/1 17:36:16
本文主要是介绍SpringBoot静态资源源码解析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
SpringBoot加载静态资源有关的自动配置类为WebMvcAutoConfiguration中的addResourceHandlers()方法
WebMvcAutoConfiguration的properties类为@EnableConfigurationProperties({ WebMvcProperties.class, WebProperties.class })
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/"); addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> { registration.addResourceLocations(this.resourceProperties.getStaticLocations()); if (this.servletContext != null) { ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION); registration.addResourceLocations(resource); } }); }
默认配置
方式一
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
请求方式
http://localhost:8080/webjars/jquery/3.4.1/AUTHORS.txt
方式二
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> { registration.addResourceLocations(this.resourceProperties.getStaticLocations()); if (this.servletContext != null) { ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION); registration.addResourceLocations(resource); } });
this.mvcProperties.getStaticPathPattern()->private String staticPathPattern = "/**"; 来自于WebMvcProperties.java
this.resourceProperties.getStaticLocations() | public String[] getStaticLocations() { return this.staticLocations; } | private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS; | private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; 来自于WebProperties.java
请求方式:
http://localhost:8080/**
资源路径优先级
resources>static>public
上传的文件>图片>公共资源
一旦在application.yaml中定义了,那么默认配置都不会生效
spring: mvc: static-path-pattern: /**
这篇关于SpringBoot静态资源源码解析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Mybatis官方生成器资料详解与应用教程
- 2024-11-26Mybatis一级缓存资料详解与实战教程
- 2024-11-26Mybatis一级缓存资料详解:新手快速入门
- 2024-11-26SpringBoot3+JDK17搭建后端资料详尽教程
- 2024-11-26Springboot单体架构搭建资料:新手入门教程
- 2024-11-26Springboot单体架构搭建资料详解与实战教程
- 2024-11-26Springboot框架资料:新手入门教程
- 2024-11-26Springboot企业级开发资料入门教程
- 2024-11-26SpringBoot企业级开发资料详解与实战教程
- 2024-11-26Springboot微服务资料:新手入门全攻略