核心原则
- 遵循 SOLID、DRY、KISS 和 YAGNI 原则
- 使用分层架构实现关注点分离
- 使用 DTO 在层间传递数据
- 统一异常处理和响应格式
- 遵循 OWASP 安全最佳实践
技术栈
- 框架:Spring Boot 3
- 语言:Java 17+
- ORM:Spring Data JPA
- 数据库:PostgreSQL / MySQL
- 构建工具:Maven / Gradle
- 工具:Lombok
最佳实践
分层架构
src/main/java/
├── controller/ # REST 控制器
├── service/ # 服务接口
│ └── impl/ # 服务实现
├── repository/ # 数据访问层
├── model/ # 实体类
├── dto/ # 数据传输对象
├── config/ # 配置类
└── exception/ # 异常处理
实体类
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty
@Size(max = 100)
@Column(nullable = false)
private String name;
@Email
@Column(unique = true)
private String email;
@ManyToOne(fetch = FetchType.LAZY)
private Department department;
}
Repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@EntityGraph(attributePaths = {"department"})
Optional<User> findWithDepartmentById(Long id);
@Query("SELECT new com.example.dto.UserDTO(u.id, u.name, u.email) FROM User u")
List<UserDTO> findAllUserDTOs();
}
Service
public interface UserService {
UserDTO getUserById(Long id);
UserDTO createUser(UserCreateDTO dto);
}
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public UserDTO getUserById(Long id) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found"));
return UserDTO.from(user);
}
}
Controller
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<UserDTO>> getUser(@PathVariable Long id) {
UserDTO user = userService.getUserById(id);
return ResponseEntity.ok(ApiResponse.success(user));
}
}
关键约定
实体规范
- 使用 @Entity 注解实体类
- 使用 @Data (Lombok) 减少样板代码
- 使用 FetchType.LAZY 处理关联
- 正确注解属性进行验证
Repository 规范
- Repository 必须是接口类型
- 继承 JpaRepository
- 使用 JPQL 编写查询
- 使用 @EntityGraph 避免 N+1 问题
Service 规范
- Service 必须是接口类型
- 实现类使用 @Service 注解
- 使用 @Transactional 管理事务
- 返回 DTO 而非实体
Controller 规范
- 使用 @RestController 注解
- 返回 ApiResponse 类型的 ResponseEntity
- 在 try-catch 块中处理异常
统一响应格式
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResponse<T> {
private boolean result;
private String message;
private T data;
public static <T> ApiResponse<T> success(T data) {
return new ApiResponse<>(true, "成功", data);
}
public static <T> ApiResponse<T> error(String message) {
return new ApiResponse<>(false, message, null);
}
}
性能优化
- 使用 @EntityGraph 避免 N+1 查询
- 使用连接池管理数据库连接
- 实现缓存策略
- 使用异步处理耗时任务
安全实践
- 输入验证和清理
- 使用 Spring Security 进行认证授权
- 防止 SQL 注入和 XSS 攻击
- 敏感数据加密存储