项目结构规范
项目结构
1. 单体项目结构
user-service/
├── .git/
├── .github/ # GitHub 配置
│ └── workflows/ # CI/CD 工作流
├── .mvn/ # Maven 配置
├── docs/ # 文档
│ ├── api/ # API 文档
│ └── design/ # 设计文档
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/user/
│ │ │ ├── UserApplication.java # 启动类
│ │ │ ├── config/ # 配置类
│ │ │ │ ├── WebConfig.java
│ │ │ │ └── SecurityConfig.java
│ │ │ ├── controller/ # 控制器
│ │ │ │ └── UserController.java
│ │ │ ├── service/ # 服务层
│ │ │ │ ├── UserService.java
│ │ │ │ └── impl/
│ │ │ │ └── UserServiceImpl.java
│ │ │ ├── repository/ # 数据访问层
│ │ │ │ └── UserRepository.java
│ │ │ ├── entity/ # 实体类
│ │ │ │ └── User.java
│ │ │ ├── dto/ # 数据传输对象
│ │ │ │ ├── CreateUserRequest.java
│ │ │ │ ├── UpdateUserRequest.java
│ │ │ │ └── UserResponse.java
│ │ │ ├── vo/ # 视图对象
│ │ │ │ └── UserVO.java
│ │ │ ├── enums/ # 枚举
│ │ │ │ └── UserStatus.java
│ │ │ ├── exception/ # 异常类
│ │ │ │ ├── BusinessException.java
│ │ │ │ └── ResourceNotFoundException.java
│ │ │ ├── handler/ # 异常处理器
│ │ │ │ └── GlobalExceptionHandler.java
│ │ │ ├── util/ # 工具类
│ │ │ │ └── UserUtils.java
│ │ │ └── event/ # 事件类
│ │ │ └── UserCreatedEvent.java
│ │ └── resources/
│ │ ├── application.yml # 主配置
│ │ ├── application-dev.yml # 开发环境配置
│ │ ├── application-test.yml # 测试环境配置
│ │ ├── application-prod.yml # 生产环境配置
│ │ ├── mapper/ # MyBatis Mapper
│ │ │ └── UserMapper.xml
│ │ ├── db/ # 数据库脚本
│ │ │ └── migration/
│ │ └── static/ # 静态资源
│ └── test/
│ └── java/
│ └── com/example/user/
│ ├── controller/
│ │ └── UserControllerTest.java
│ ├── service/
│ │ └── UserServiceTest.java
│ └── integration/
│ └── UserIntegrationTest.java
├── Dockerfile # Docker 配置
├── docker-compose.yml # Docker Compose 配置
├── pom.xml # Maven 配置
├── README.md # 项目说明
├── LICENSE # 许可证
└── .gitignore # Git 忽略文件
2. 多模块项目结构
daily-article-parent/
├── .git/
├── docs/ # 文档
├── common/ # 公共模块
│ ├── common-core/ # 核心公共类
│ │ ├── src/
│ │ │ ├── main/
│ │ │ │ └── java/
│ │ │ │ └── com/example/common/
│ │ │ │ ├── result/ # 统一响应
│ │ │ │ │ └── Result.java
│ │ │ │ ├── exception/ # 公共异常
│ │ │ │ │ └── BusinessException.java
│ │ │ │ └── util/ # 公共工具
│ │ │ │ └── JsonUtils.java
│ │ └── pom.xml
│ ├── common-web/ # Web 公共类
│ │ ├── src/
│ │ │ └── main/
│ │ │ └── java/
│ │ │ └── com/example/common/
│ │ │ ├── config/ # Web 配置
│ │ │ │ └── WebConfig.java
│ │ │ └── handler/ # 统一异常处理
│ │ │ └── GlobalExceptionHandler.java
│ │ └── pom.xml
│ └── pom.xml
├── gateway/ # 网关服务
│ ├── src/
│ └── pom.xml
├── user-service/ # 用户服务
│ ├── src/
│ └── pom.xml
├── order-service/ # 订单服务
│ ├── src/
│ └── pom.xml
├── product-service/ # 商品服务
│ ├── src/
│ └── pom.xml
├── pom.xml # 父 POM
├── docker-compose.yml # Docker Compose
└── README.md
3. 微服务项目结构
microservices/
├── .github/ # GitHub 配置
│ └── workflows/
│ ├── ci.yml # CI 工作流
│ └── cd.yml # CD 工作流
├── infrastructure/ # 基础设施
│ ├── docker/ # Docker 配置
│ │ ├── gateway/
│ │ ├── user-service/
│ │ └── order-service/
│ ├── k8s/ # K8s 配置
│ │ ├── base/
│ │ └── overlays/
│ │ ├── dev/
│ │ ├── test/
│ │ └── prod/
│ └── terraform/ # IaC 配置
├── services/ # 微服务
│ ├── gateway/
│ │ ├── src/
│ │ ├── Dockerfile
│ │ └── pom.xml
│ ├── user-service/
│ │ ├── src/
│ │ ├── Dockerfile
│ │ └── pom.xml
│ └── order-service/
│ ├── src/
│ ├── Dockerfile
│ └── pom.xml
├── libs/ # 共享库
│ ├── api-gateway-starter/
│ ├── service-starter/
│ └── pom.xml
├── docs/ # 文档
│ ├── architecture/ # 架构文档
│ ├── api/ # API 文档
│ └── deployment/ # 部署文档
├── scripts/ # 脚本
│ ├── build.sh
│ ├── deploy.sh
│ └── backup.sh
├── pom.xml
├── docker-compose.yml
└── README.md
命名规范
1. 类命名
// 好的命名
public class UserController { } // 控制器
public class UserService { } // 服务
public class UserServiceImpl { } // 服务实现
public class UserRepository { } // 数据访问
public class User { } // 实体
public class CreateUserRequest { } // 请求对象
public class UserResponse { } // 响应对象
public class UserVO { } // 视图对象
public class UserDTO { } // 数据传输对象
public class BusinessException { } // 异常类
public class UserStatus { } // 枚举
public class UserUtils { } // 工具类
// 不好的命名
public class UserControllerImpl { } // 控制器不需要 Impl
public class UserMgr { } // 避免缩写
public class UserData { } // 含义不明确
2. 方法命名
// 好的命名
public User getUserById(Long id); // 查询
public List<User> getAllUsers(); // 查询列表
public User createUser(CreateUserRequest request); // 创建
public void updateUser(Long id, UpdateUserRequest request); // 更新
public void deleteUser(Long id); // 删除
public boolean existsById(Long id); // 存在检查
public Page<User> listUsers(Pageable pageable); // 分页查询
// 不好的命名
public User find(Long id); // 含义不明确
public User get(Long id); // 含义不明确
public void delete(Long id); // 缺少业务含义
3. 变量命名
// 好的命名
private Long userId; // 有意义的变量名
private List<User> users; // 集合用复数
private boolean isActive; // 布尔值用 is 前缀
private String userName; // 驼峰命名
private static final int MAX_RETRY = 3; // 常量用大写
// 不好的命名
private Long id; // 缺少上下文
private List<User> list; // 含义不明确
private boolean flag; // 含义不明确
private String NAME; // 非常量用大写
4. 包命名
// 好的命名
package com.example.user.controller;
package com.example.user.service;
package com.example.user.repository;
package com.example.user.entity;
package com.example.user.dto;
// 不好的命名
package com.example.user.Controller; // 包名小写
package com.example.user.ctrl; // 避免缩写
package com.example.user; // 缺少子包
代码规范
1. 注释规范
/**
* 用户服务接口
*
* @author John Doe
* @since 1.0.0
*/
public interface UserService {
/**
* 根据 ID 查询用户
*
* @param id 用户 ID
* @return 用户信息
* @throws ResourceNotFoundException 用户不存在
*/
User getUserById(Long id);
/**
* 创建用户
*
* @param request 创建用户请求
* @return 创建的用户
* @throws BusinessException 业务异常
*/
User createUser(CreateUserRequest request);
}
2. 异常处理
// 好的异常处理
try {
User user = userService.getUserById(id);
return Result.success(user);
} catch (ResourceNotFoundException e) {
log.warn("用户不存在,id={}", id);
return Result.fail("用户不存在");
} catch (BusinessException e) {
log.error("业务异常,id={}", id, e);
return Result.fail(e.getMessage());
} catch (Exception e) {
log.error("系统异常,id={}", id, e);
return Result.fail("系统异常");
}
// 不好的异常处理
try {
User user = userService.getUserById(id);
return Result.success(user);
} catch (Exception e) {
e.printStackTrace(); // 避免打印堆栈
return Result.fail("error"); // 错误信息不明确
}
3. 日志规范
// 好的日志
log.info("用户创建成功,userId={}", user.getId());
log.warn("用户不存在,userId={}", userId);
log.error("用户创建失败,userId={}", userId, e);
// 不好的日志
log.info("user created"); // 信息不完整
System.out.println("error"); // 避免使用 System.out
log.debug(e); // 避免直接打印异常
配置规范
1. 配置文件
# application.yml
spring:
application:
name: user-service
profiles:
active: ${SPRING_PROFILES_ACTIVE:dev}
# application-dev.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/user_db
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
# application-prod.yml
spring:
datasource:
url: jdbc:mysql://mysql:3306/user_db
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
jpa:
hibernate:
ddl-auto: validate
show-sql: false
2. 环境变量
# .env
# 数据库配置
DB_HOST=mysql
DB_PORT=3306
DB_NAME=user_db
DB_USERNAME=app_user
DB_PASSWORD=S3cr3tP@ssw0rd
# Redis 配置
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=S3cr3tP@ssw0rd
# 服务配置
SPRING_PROFILES_ACTIVE=prod
SERVER_PORT=8080
3. Docker 配置
# Dockerfile
FROM openjdk:17-jdk-slim AS builder
WORKDIR /app
COPY . .
RUN ./mvnw clean package -DskipTests
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", \
"-Djava.security.egd=file:/dev/./urandom", \
"-jar", "app.jar"]
文档规范
1. README 规范
# User Service
用户服务,提供用户管理相关功能。
## 快速开始
### 环境要求
- JDK 17+
- Maven 3.6+
- MySQL 8.0+
- Redis 6+
### 本地运行
```bash
# 克隆项目
git clone https://github.com/example/user-service.git
# 安装依赖
mvn clean install
# 运行
mvn spring-boot:run
配置
编辑 src/main/resources/application.yml 配置数据库和 Redis。
API 文档
访问 http://localhost:8080/swagger-ui.html 查看 API 文档。
测试
# 单元测试
mvn test
# 集成测试
mvn verify
部署
# 构建 Docker 镜像
docker build -t user-service:latest .
# 运行容器
docker run -p 8080:8080 user-service:latest
贡献
- Fork 项目
- 创建特性分支
- 提交更改
- 推送到分支
- 创建 Pull Request
许可证
Apache License 2.0
### 2. API 文档
```yaml
# OpenAPI 规范
openapi: 3.0.0
info:
title: User Service API
description: 用户服务 API 文档
version: 1.0.0
contact:
name: API Support
email: support@example.com
servers:
- url: http://localhost:8080/api
description: 本地环境
- url: https://api.example.com/api
description: 生产环境
paths:
/users/{id}:
get:
summary: 获取用户信息
description: 根据用户 ID 获取用户详细信息
tags:
- 用户管理
parameters:
- name: id
in: path
required: true
description: 用户 ID
schema:
type: integer
format: int64
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/UserResponse'
'404':
description: 用户不存在
最佳实践
1. 代码复用
// 提取公共方法
public abstract class BaseService {
protected <T> T notNull(T object, String fieldName) {
if (object == null) {
throw new IllegalArgumentException(fieldName + " 不能为空");
}
return object;
}
protected void notEmpty(String string, String fieldName) {
if (StringUtils.isEmpty(string)) {
throw new IllegalArgumentException(fieldName + " 不能为空");
}
}
}
// 使用
@Service
public class UserService extends BaseService {
public User getUserById(Long id) {
notNull(id, "用户 ID");
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
}
}
2. 依赖管理
<!-- 父 POM 统一管理依赖版本 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>common-core</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
3. 构建优化
<!-- Maven 构建优化 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layers>
<enabled>true</enabled>
</layers>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
<parameters>true</parameters>
</configuration>
</plugin>
</plugins>
</build>
总结
规范的项目结构是微服务开发的基础,包括目录结构、命名规范、代码规范、配置规范等。
遵循统一的规范可以提高开发效率、降低维护成本、提升代码质量。
建立完善的文档和最佳实践,有助于团队协作和知识传承。