在 Spring Boot 中,static
和 public
目录都用于存放静态资源(如 HTML、CSS、JavaScript、图片等文件),但它们在使用上有一些细微的区别。以下是它们的详细对比:
1. 默认优先级
Spring Boot 会按照以下优先级加载静态资源:
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
如果多个目录中存在同名文件,Spring Boot 会优先加载优先级更高的目录中的文件。
2. 使用场景
static
目录
- 推荐用途:存放前端静态资源(如 HTML、CSS、JS 文件)。
- 特点:
- 是 Spring Boot 默认的静态资源目录之一。
- 适合存放与前端相关的静态文件。
- 优先级高于
public
目录。
public
目录
- 推荐用途:存放公共资源(如图片、字体、下载文件等)。
- 特点:
- 是 Spring Boot 默认的静态资源目录之一。
- 适合存放不常变动或通用的静态资源。
- 优先级低于
static
目录。
3. 示例
假设项目结构如下:
src/main/resources/
├── static/
│ └── index.html
└── public/└── images/└── logo.png
访问方式
index.html
的访问 URL:http://localhost:8080/index.html
logo.png
的访问 URL:http://localhost:8080/images/logo.png
4. 自定义静态资源路径
如果需要自定义静态资源路径,可以在 application.properties
或 application.yml
中配置:
application.properties
spring.web.resources.static-locations=classpath:/custom-static/
application.yml
spring:web:resources:static-locations: classpath:/custom-static/
配置后,Spring Boot 会从 custom-static
目录加载静态资源,而不是默认的 static
或 public
目录。
5. 总结
特性 | static 目录 | public 目录 |
---|---|---|
优先级 | 较高 | 较低 |
推荐用途 | 前端静态资源(HTML、CSS、JS) | 公共资源(图片、字体、下载文件) |
默认路径 | classpath:/static/ | classpath:/public/ |
访问方式 | http://localhost:8080/filename | http://localhost:8080/filename |
选择建议
- 如果项目主要是前端应用,推荐将静态资源放在
static
目录。 - 如果需要存放通用的公共资源(如图片、字体等),可以放在
public
目录。 - 如果需要更灵活的管理,可以通过配置自定义静态资源路径。