Springboot加载静态资源

Springboot加载静态资源

静态资源映射路径:
classpath:/META-INF/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
源码分析:
  1. 找到springboot加载静态资源的自动配置组件类 WebMvcAutoConfiguration,该类中有个加载静态资源的方法:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
	//如果我们配置了加载静态资源的路径,则默认作废
	if (!this.resourceProperties.isAddMappings()) {
		logger.debug("Default resource handling disabled");
		return;
	}
	//使用webjars方式加载静态资源,略过
	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);
		}
	});
}
  1. 重点来看这行代码:读取默认的静态资源配置路径
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
  1. 点进这个方法,可得知返回了一个常量数组,而数组内存放的就是加载资源的路径映射
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/" };
  1. 加载静态资源的优先级:
    通过在以上的资源目录下分别放置一个同名静态资源(内容不同)来测试加载的优先级
    得出优先级顺序就是数组存放的先后顺序,即:从上到下,优先级逐减
classpath:/META-INF/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值