java-springboot
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSpring Boot Best Practices
Spring Boot 最佳实践
Your goal is to help me write high-quality Spring Boot applications by following established best practices.
本文旨在帮助你遵循既定的最佳实践,编写高质量的Spring Boot应用程序。
Project Setup & Structure
项目搭建与结构
- Build Tool: Use Maven () or Gradle (
pom.xml) for dependency management.build.gradle - Starters: Use Spring Boot starters (e.g., ,
spring-boot-starter-web) to simplify dependency management.spring-boot-starter-data-jpa - Package Structure: Organize code by feature/domain (e.g., ,
com.example.app.order) rather than by layer (e.g.,com.example.app.user,com.example.app.controller).com.example.app.service
- 构建工具: 使用Maven()或Gradle(
pom.xml)进行依赖管理。build.gradle - Starter依赖: 使用Spring Boot Starter依赖(例如、
spring-boot-starter-web)简化依赖管理。spring-boot-starter-data-jpa - 包结构: 按功能/领域组织代码(例如、
com.example.app.order),而非按分层(例如com.example.app.user、com.example.app.controller)。com.example.app.service
Dependency Injection & Components
依赖注入与组件
- Constructor Injection: Always use constructor-based injection for required dependencies. This makes components easier to test and dependencies explicit.
- Immutability: Declare dependency fields as .
private final - Component Stereotypes: Use ,
@Component,@Service, and@Repository/@Controllerannotations appropriately to define beans.@RestController
- 构造函数注入: 对于必需的依赖项,始终使用基于构造函数的注入。这让组件更易于测试,且依赖关系更明确。
- 不可变性: 将依赖字段声明为。
private final - 组件注解: 合理使用、
@Component、@Service以及@Repository/@Controller注解来定义Bean。@RestController
Configuration
配置管理
- Externalized Configuration: Use (or
application.yml) for configuration. YAML is often preferred for its readability and hierarchical structure.application.properties - Type-Safe Properties: Use to bind configuration to strongly-typed Java objects.
@ConfigurationProperties - Profiles: Use Spring Profiles (,
application-dev.yml) to manage environment-specific configurations.application-prod.yml - Secrets Management: Do not hardcode secrets. Use environment variables, or a dedicated secret management tool like HashiCorp Vault or AWS Secrets Manager.
- 外部化配置: 使用(或
application.yml)进行配置。YAML因其可读性和分层结构常被优先选择。application.properties - 类型安全属性: 使用将配置绑定到强类型Java对象。
@ConfigurationProperties - 环境配置文件: 使用Spring Profiles(、
application-dev.yml)管理特定环境的配置。application-prod.yml - 密钥管理: 不要硬编码密钥。使用环境变量,或专用密钥管理工具如HashiCorp Vault、AWS Secrets Manager。
Web Layer (Controllers)
Web层(控制器)
- RESTful APIs: Design clear and consistent RESTful endpoints.
- DTOs (Data Transfer Objects): Use DTOs to expose and consume data in the API layer. Do not expose JPA entities directly to the client.
- Validation: Use Java Bean Validation (JSR 380) with annotations (,
@Valid,@NotNull) on DTOs to validate request payloads.@Size - Error Handling: Implement a global exception handler using and
@ControllerAdviceto provide consistent error responses.@ExceptionHandler
- RESTful API: 设计清晰且一致的RESTful接口。
- 数据传输对象(DTO): 在API层使用DTO来暴露和接收数据。不要直接向客户端暴露JPA实体。
- 参数校验: 在DTO上使用Java Bean Validation(JSR 380)注解(如、
@Valid、@NotNull)验证请求体。@Size - 异常处理: 使用和
@ControllerAdvice实现全局异常处理器,提供一致的错误响应。@ExceptionHandler
Service Layer
服务层
- Business Logic: Encapsulate all business logic within classes.
@Service - Statelessness: Services should be stateless.
- Transaction Management: Use on service methods to manage database transactions declaratively. Apply it at the most granular level necessary.
@Transactional
- 业务逻辑: 将所有业务逻辑封装在类中。
@Service - 无状态: 服务应保持无状态。
- 事务管理: 在服务方法上使用声明式管理数据库事务。仅在必要的最细粒度级别上应用。
@Transactional
Data Layer (Repositories)
数据层(仓库)
- Spring Data JPA: Use Spring Data JPA repositories by extending or
JpaRepositoryfor standard database operations.CrudRepository - Custom Queries: For complex queries, use or the JPA Criteria API.
@Query - Projections: Use DTO projections to fetch only the necessary data from the database.
- Spring Data JPA: 通过继承或
JpaRepository使用Spring Data JPA仓库执行标准数据库操作。CrudRepository - 自定义查询: 对于复杂查询,使用或JPA Criteria API。
@Query - 投影查询: 使用DTO投影仅从数据库获取必要的数据。
Logging
日志管理
- SLF4J: Use the SLF4J API for logging.
- Logger Declaration:
private static final Logger logger = LoggerFactory.getLogger(MyClass.class); - Parameterized Logging: Use parameterized messages () instead of string concatenation to improve performance.
logger.info("Processing user {}...", userId);
- SLF4J: 使用SLF4J API进行日志记录。
- 日志对象声明:
private static final Logger logger = LoggerFactory.getLogger(MyClass.class); - 参数化日志: 使用参数化消息(如)替代字符串拼接,提升性能。
logger.info("Processing user {}...", userId);
Testing
测试
- Unit Tests: Write unit tests for services and components using JUnit 5 and a mocking framework like Mockito.
- Integration Tests: Use for integration tests that load the Spring application context.
@SpringBootTest - Test Slices: Use test slice annotations like (for controllers) or
@WebMvcTest(for repositories) to test specific parts of the application in isolation.@DataJpaTest - Testcontainers: Consider using Testcontainers for reliable integration tests with real databases, message brokers, etc.
- 单元测试: 使用JUnit 5和Mockito等模拟框架为服务和组件编写单元测试。
- 集成测试: 使用加载Spring应用上下文进行集成测试。
@SpringBootTest - 测试切片: 使用测试切片注解如(针对控制器)或
@WebMvcTest(针对仓库),隔离测试应用的特定部分。@DataJpaTest - Testcontainers: 考虑使用Testcontainers与真实数据库、消息队列等进行可靠的集成测试。
Security
安全
- Spring Security: Use Spring Security for authentication and authorization.
- Password Encoding: Always encode passwords using a strong hashing algorithm like BCrypt.
- Input Sanitization: Prevent SQL injection by using Spring Data JPA or parameterized queries. Prevent Cross-Site Scripting (XSS) by properly encoding output.
- Spring Security: 使用Spring Security进行身份验证和授权。
- 密码加密: 始终使用BCrypt等强哈希算法对密码进行加密。
- 输入净化: 使用Spring Data JPA或参数化查询防止SQL注入。通过正确编码输出防止跨站脚本攻击(XSS)。