SpringBoot项目结构
SpringBoot 项目遵循约定优于配置原则,目录结构标准化。
标准目录结构
Java
my-app/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/
│ │ │ ├── MyApplication.java # 启动类
│ │ │ ├── controller/ # 控制器
│ │ │ ├── service/ # 业务层
│ │ │ ├── repository/ # 数据访问层
│ │ │ ├── entity/ # 实体类
│ │ │ ├── config/ # 配置类
│ │ │ └── util/ # 工具类
│ │ └── resources/
│ │ ├── application.yml # 配置文件
│ │ ├── static/ # 静态资源
│ │ ├── templates/ # 模板文件
│ │ └── public/ # 公共资源
│ └── test/
│ └── java/
│ └── com/example/
│ └── MyApplicationTests.java
├── target/ # 编译输出
├── pom.xml # Maven配置
└── README.md # 项目说明
目录职责说明
| 目录 | 职责 |
|---|---|
| src/main/java | 源代码目录 |
| src/main/resources | 资源文件目录 |
| src/test/java | 测试代码目录 |
| static | 静态资源(CSS/JS/图片) |
| templates | 模板文件(Thymeleaf等) |
| public | Web根目录资源 |
启动类位置
启动类应放在根包下:
text
com/example/
├── MyApplication.java # ✅ 正确:根包位置
├── controller/
├── service/
com/
├── example/
│ └── controller/
├── MyApplication.java # ❌ 错误:不在根包
启动类在根包时,@SpringBootApplication 自动扫描同包及子包下的组件。
resources目录详解
text
resources/
├── application.yml # 主配置文件
├── application-dev.yml # 开发环境配置
├── application-prod.yml # 生产环境配置
├── static/
│ ├── css/
│ ├── js/
│ └── images/
├── templates/
│ ├── index.html
│ └── error/
│ └── 500.html
├── public/
│ └── favicon.ico
└── mybatis/
│ └── mapper/
│ └── UserMapper.xml
包分层规范
text
// controller层:接收请求
@RestController
public class UserController { }
// service层:业务逻辑
@Service
public class UserService { }
// repository层:数据访问
@Repository
public interface UserRepository { }
// entity层:实体类
@Entity
public class User { }
// config层:配置类
@Configuration
public class WebConfig { }
// util层:工具类
public class StringUtils { }
target目录
text
target/
├── classes/ # 编译后的class文件
│ ├── com/example/
│ └── application.yml
├── generated-sources/
├── maven-status/
└── my-app-1.0.0.jar # 打包产物
资源访问路径
| 资源位置 | 访问路径 |
|---|---|
| static/index.html | /index.html |
| public/favicon.ico | /favicon.ico |
| templates/home.html | 需Controller渲染 |
类命名规范
| 类型 | 命名示例 |
|---|---|
| Controller | UserController |
| Service | UserService |
| Repository | UserRepository |
| Entity | User |
| DTO | UserDTO |
| Config | WebConfig |
| Exception | BusinessException |
要点总结
- 启动类放在根包,自动扫描子包组件
- static存放静态资源,templates存放模板
- controller/service/repository分层清晰
- 遵循命名规范,提高可读性
📝 发现内容有误?点击此处直接编辑