在SpringBoot中我们一般通过以下方式来处理静态资源
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
优先级从高到低
默认使用是static
因为优先级的关系
一般public放用户界面
static我们放图片等
至于另外两个就放一些核心的部分
jar包一般使用的是webjars的方式
比如jquery的jar包
我们想访问这个jquery.js只需要这样访问
localhost:8080/webjars/jquery/3.3.1/jquery.js
我们很容易发现 META-INF/resources是不需要写的
同理 访问我们自己的静态资源也不需要
比如想要访问1.js 直接从以上四个路径中挑一个放入1.js
然后localhost:8080/1.js 即可
源码
在WebMvcAutoConfiguration下
有这么个方法
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl).setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl).setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
}
}
}
这个方法判断了三种情况
- 自定义路径
- 使用webjars
- 我们放置在上述的几种地方
我们点开
getStaticLocations()
得到
public String[] getStaticLocations() {
return this.staticLocations;
}
再点staticLocations
发现这两个属性
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
我们再看构造方法
public Resources() {
this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
//一些其他的东西 我没有CV
}
就可以得到我们上述的路径了