springboot通过源码查看静态资源加载原理

spingboot静态资源加载

源码展示

WebMvcAutoConfiguration.java源码中找到addResourceHandlers方法

   	public void addResourceHandlers(ResourceHandlerRegistry registry) {
   		//this.resourceProperties.isAddMappings()如果对resourceProperties进行配置,那么就会禁用默认资源处理
   		//resourceProperties.isAddMappings() 默认为true
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			//获取缓存配置的资源处理程序提供的资源缓存周期。
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			//getCache().getCachecontrol()缓存控制HTTP头配置
			//以下一段是将classpath:/META-INF/resources/webjars/映射为/webjars/**
			//只要存在/META-INF/resources/webjars/都可以通过/webjars/**进行访问
			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));
			}
			//默认值
			//staticPathPattern = "/**"
			//String[] staticLocations ={ "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/" }
			//以下这段代码可以通过"/**"访问staticLocations包含 的路径下去找资源
			//资源访问存在优先级
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}

在Springboot,我们可以使用以下方式处理静态资源
webjars目录的访问地址:

locatlhost:8080/wabjars/**

META-INF/resources/ ,public ,static , /** ,resources 的目录访问地址

localhost:8080/ 

访问优先级

通过源码,我们发现staticLocations 存在的路径中都会映射为"/**",当其他存在相同文件时,则会按照以下的顺序进行进行访问

  1. META-INF/resources/
  2. resources
  3. static(默认)
  4. public

还有webjars的加载方式请看这篇博文springboot使用webjars加载资源

如有不足之处,请指出,谢谢!
每天进步一点点。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值