java-spring-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJava Spring Development Best Practices
Java Spring开发最佳实践
Core Principles
核心原则
- Write clean, efficient, and well-documented Java code with accurate Spring Boot examples
- Use Spring Boot 3.x with Java 17+ features (records, sealed classes, pattern matching)
- Prefer constructor injection over field injection for better testability
- Follow SOLID principles and RESTful API design patterns
- Design for microservices architecture suitability
- 编写简洁、高效且文档完善的Java代码,并附带准确的Spring Boot示例
- 使用Spring Boot 3.x及Java 17+特性(records、密封类、模式匹配)
- 优先使用构造函数注入而非字段注入,以提升可测试性
- 遵循SOLID原则和RESTful API设计模式
- 设计时考虑微服务架构的适配性
Project Structure
项目结构
Organize code using the standard layered pattern:
project/
├── controllers/ # REST controllers
├── services/ # Business logic
├── repositories/ # Data access layer
├── models/ # Domain entities and DTOs
└── configurations/ # Spring configurations采用标准分层模式组织代码:
project/
├── controllers/ # REST控制器
├── services/ # 业务逻辑层
├── repositories/ # 数据访问层
├── models/ # 领域实体与DTO
└── configurations/ # Spring配置Dependency Injection
依赖注入
- Use constructor injection for required dependencies
- Leverage with Lombok for cleaner code
@RequiredArgsConstructor - Keep constructors simple and avoid logic in them
- Use when multiple implementations exist
@Qualifier
- 对必需依赖使用构造函数注入
- 结合Lombok的简化代码
@RequiredArgsConstructor - 保持构造函数简洁,避免在其中编写逻辑
- 当存在多个实现时使用
@Qualifier
REST API Design
REST API设计
- Use appropriate HTTP methods (GET, POST, PUT, DELETE, PATCH)
- Return proper HTTP status codes
- Implement consistent error response format
- Use DTOs to control API contract
- Version APIs when needed
- 使用合适的HTTP方法(GET、POST、PUT、DELETE、PATCH)
- 返回正确的HTTP状态码
- 实现统一的错误响应格式
- 使用DTO控制API契约
- 必要时对API进行版本化
Data Access
数据访问
Spring Data JPA
Spring Data JPA
- Define proper entity relationships (@OneToMany, @ManyToOne, etc.)
- Use lazy loading appropriately to avoid N+1 queries
- Implement pagination for large result sets
- Use query methods and @Query for custom queries
- 定义正确的实体关系(@OneToMany、@ManyToOne等)
- 合理使用懒加载以避免N+1查询问题
- 为大数据集实现分页功能
- 使用查询方法和@Query实现自定义查询
Database Migrations
数据库迁移
- Use Flyway or Liquibase for schema migrations
- Version migration scripts properly
- Never modify existing migrations
- Test migrations in development before production
- 使用Flyway或Liquibase进行 schema 迁移
- 对迁移脚本进行正确的版本控制
- 绝不修改已存在的迁移脚本
- 生产环境前先在开发环境测试迁移
Security
安全
Spring Security
Spring Security
- Implement authentication and authorization properly
- Use BCrypt for password encoding
- Configure CORS appropriately
- Protect endpoints based on roles/permissions
- Use HTTPS in production
- 正确实现认证与授权
- 使用BCrypt进行密码加密
- 合理配置CORS
- 根据角色/权限保护端点
- 生产环境使用HTTPS
Secure Coding
安全编码
- Validate all user inputs
- Sanitize data to prevent injection attacks
- Avoid exposing sensitive information in responses
- Use parameterized queries
- 验证所有用户输入
- 对数据进行清理以防止注入攻击
- 避免在响应中暴露敏感信息
- 使用参数化查询
Testing
测试
Unit Testing
单元测试
- Use JUnit 5 for unit tests
- Mock dependencies with Mockito
- Test business logic thoroughly
- Follow Given-When-Then pattern
- 使用JUnit 5进行单元测试
- 用Mockito模拟依赖
- 全面测试业务逻辑
- 遵循Given-When-Then模式
Integration Testing
集成测试
- Use @SpringBootTest for integration tests
- Use MockMvc for web layer testing
- Test database operations with test containers
- Test security configurations
- 使用@SpringBootTest进行集成测试
- 用MockMvc测试Web层
- 结合测试容器测试数据库操作
- 测试安全配置
Performance
性能
Caching
缓存
- Use Spring Cache abstraction
- Configure appropriate cache providers (Redis, Caffeine)
- Set proper TTL for cached data
- Implement cache eviction strategies
- 使用Spring Cache抽象层
- 配置合适的缓存提供者(Redis、Caffeine)
- 为缓存数据设置合理的TTL
- 实现缓存淘汰策略
Async Processing
异步处理
- Use @Async for non-blocking operations
- Configure thread pools appropriately
- Handle exceptions in async methods
- Consider using reactive patterns for high concurrency
- 使用@Async实现非阻塞操作
- 合理配置线程池
- 处理异步方法中的异常
- 高并发场景考虑使用响应式模式
Logging and Monitoring
日志与监控
Logging
日志
- Use SLF4J with Logback
- Log at appropriate levels
- Include correlation IDs for tracing
- Avoid logging sensitive data
- 使用SLF4J结合Logback
- 按合适的级别记录日志
- 包含关联ID用于追踪
- 避免记录敏感数据
Monitoring
监控
- Use Spring Boot Actuator for health and metrics
- Export metrics to monitoring systems
- Set up proper health checks
- Monitor application performance
- 使用Spring Boot Actuator获取健康状态与指标
- 将指标导出至监控系统
- 设置合理的健康检查
- 监控应用性能
API Documentation
API文档
- Use Springdoc OpenAPI for API documentation
- Document all endpoints with descriptions
- Include request/response examples
- Keep documentation up to date with code
- 使用Springdoc OpenAPI生成API文档
- 为所有端点添加描述文档
- 包含请求/响应示例
- 保持文档与代码同步