spring boot 的项目是将静态资源打包到.jar 的文件包中, 项目中有碰到需要使用外部静态资源的情况,使用外部资源的一直老出问题,查了google 后发现是指定的方式不对。

静态资源配置

resource/static 进行映射,springboot 默认优先级:

/META-INF/resources/
/resources/
/static/
/public/

spring 属性合配 resources 配置
1.本项目包含路径:

1
2
3
4
5
spring:
mvc:
static-path-pattern: /late
resources:
static-locations: classpath:/templates/dist/

这两天遇到的坑

2.指定项目外的磁盘路径
如果要映射本地磁盘路径,可以使用,注意必须得有 file:, 注意必须得有file:,注意必须得有file: 否则 404, 重要事情说三遍。

1
2
3
4
5
spring:
mvc:
static-path-pattern: /late
resources:
static-locations: file:/templates/dist/

浏览器的访问路径通过这个就可以改。

static-path-pattern

3.还有一种方式是打包到 webjars 中,不过一样是费劲的事,不如直接指定外部磁盘路径,使用 nginx 做转换成功访问静态文件,但是配置更麻烦。