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

2023-05-16

今天刚到学校,补一篇博客,小博客🧐
关于路径问题非常简单,直接上源码吧
同样是在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之类的

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐