springBoot加载静态资源

springboot版本:2.0.8
官方文档

springboot 默认静态资源位置

根据springboot的官方文档,默认静态资源的路径为:spring.resources.static-locations=classpath:/static (or classpath:/public or classpath:/resources or classpath:/META-INF/resources)
若要访问这些静态资源还需进行如下配置:

1
spring.mvc.static-path-pattern=/static/**

通过代码修改

以增加 /myres/* 映射到 classpath:/myres/* 为例的代码处理为:
实现类继承 WebMvcConfigurerAdapter 并重写方法 addResourceHandlers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
public class MyWebAppConfigurer
extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {


registry.addResourceHandler("/testStatic/**").addResourceLocations("classpath:/testStatic/");
//文件磁盘图片url 映射
//配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
//需要在"D:\\picpath\\"前加"file:///"
registry.addResourceHandler("/image/**").addResourceLocations("file:///D:\\picpath\\");
}
}

这样使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用。

参考

静态资源的访问和配置

打赏

请我喝杯咖啡吧~

支付宝
微信