static-path-pattern
在 Spring Boot 中,spring.resources.static-path-pattern
配置项用于设置静态资源的 URL 路径模式。当访问一个静态资源时,Spring Boot 会根据这个配置来匹配请求的路径。
例如,Spring Boot 默认会将 src/main/resources/static
下的文件暴露为静态资源,路径是 /static/*
。可以通过配置 spring.resources.static-path-pattern
来修改这个路径模式,使静态资源可以在自定义的路径下访问。
复制编辑
spring.resources.static-path-pattern=/custom/path/**
示例
如果你将 static-path-pattern
设置为 /assets/**
,那么访问 src/main/resources/static
中的文件时,URL 路径就会变成:
默认:
http://localhost:8080/index.html
设置后:
http://localhost:8080/assets/index.html
这意味着你可以自定义静态资源的访问路径,避免使用默认的 /static/**
路径。
适用场景:
需要更改默认静态资源访问路径时。
避免和其他路由冲突时。
提高 URL 结构的整洁性和可读性时。
spring.resources.static-locations
配置项用于指定 Spring Boot 应用中静态资源文件的存放路径。这个配置项告诉 Spring Boot 在启动时在哪里查找静态资源文件,例如 HTML、CSS、JavaScript 文件、图片等。
默认行为:
Spring Boot 默认会从以下几个目录中查找静态资源(按照优先级顺序):
classpath:/static/
classpath:/public/
classpath:/resources/
classpath:/META-INF/resources/
这些目录都位于 src/main/resources
目录下(或者 JAR 包内),并且 Spring Boot 会自动将这些目录下的文件暴露为静态资源,供 Web 应用访问。
spring.resources.static-locations
通过配置 spring.resources.static-locations
,你可以指定自定义的静态资源路径,可以是本地文件路径,也可以是类路径下的路径,或者多个路径。如果需要将静态资源放在非默认位置,或者需要从多个位置加载资源时,这个配置非常有用。
配置示例:
1. 配置为本地路径properties
复制编辑
spring.resources.static-locations=file:/opt/static/,file:/home/user/static/
这将使 Spring Boot 在启动时去查找 /opt/static/
和 /home/user/static/
目录中的静态资源。
2. 配置为类路径中的目录
复制编辑
spring.resources.static-locations=classpath:/static/,classpath:/public/
这将告诉 Spring Boot 去类路径下查找 static
和 public
目录中的静态资源文件。
3. 配置多个路径(文件路径 + 类路径)
spring.resources.static-locations=file:/opt/static/,classpath:/custom_static/
这将让 Spring Boot 从 /opt/static/
目录和类路径下的 custom_static
目录中查找静态资源。
需要注意:
如果没有显式配置
spring.resources.static-locations
,Spring Boot 会使用默认路径:classpath:/static/
、classpath:/public/
等。static-locations
需要以classpath:
或file:
开头,表示是类路径或者文件系统路径。
配置场景:
当你的静态资源不在默认的
static
或public
目录下时。需要将静态资源从多个目录加载时。
需要将静态资源从外部文件系统目录加载时(如某个共享目录或者 CDN)。
总结来说,spring.resources.static-locations
配置项允许你定义 Spring Boot 应用查找静态资源的路径,灵活控制静态资源的位置,以适应不同的部署需求。