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静态资源源码解析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程