栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

通过源码了解springboot静态资源导入的几种方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过源码了解springboot静态资源导入的几种方式

今天刚到学校,补一篇博客,小博客類
关于路径问题非常简单,直接上源码吧
同样是在spring.factories里找
如果不知道在哪里找,以及该文件的重要性这里不概述太多,路径在这:

在自动配置里就有这个文件
点开之后找到:WebMvcAutoConfiguration

找到和路径配置有关的代码:
这段代码就是所有的重点

@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);
		}
	});
}

分析:
1️⃣

if (!this.resourceProperties.isAddMappings()) {
	logger.debug("Default resource handling disabled");
	return;
}

目录自定义:

直接就修改即可,如果不修改的话使用默认的就是:在当前目录下的都可以识别,你也可以自定义‍♀️

后面的webjars就是通过导入maven的方式来导入资源,但是这种方法已经不太常用了,这里不解释噢

2️⃣
同样在这段代码

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);
		}

 getStaticPathPattern()指的就是/**

3️⃣
 addResourceLocations(resource)
同样在WebMvcAutoConfiguration打开WebProperties

打开Resources类,这里就有4个路径!这4个路径放的就是可以识别静态资源的路径

classpath路径指的就是resources下面的文件,默认的话只要打开一个spring boot文件就会生成:

默认使用的是上述4个路径中的第三个‍♀️

这样这三个目录下的都可以访问的到,优先级为:
resources > static > public

一般我的习惯就是:
public 下放一些公共的资源,比如一些js之类的
static下放一些静态资源,比如图片
resources就放一些上传的文件,uoload之类的

当然如果你都自定义了,那么其他的所有的路径就都失效了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/750758.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号