java-springboot

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Spring 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 (
    pom.xml
    ) or Gradle (
    build.gradle
    ) for dependency management.
  • Starters: Use Spring Boot starters (e.g.,
    spring-boot-starter-web
    ,
    spring-boot-starter-data-jpa
    ) to simplify dependency management.
  • Package Structure: Organize code by feature/domain (e.g.,
    com.example.app.order
    ,
    com.example.app.user
    ) rather than by layer (e.g.,
    com.example.app.controller
    ,
    com.example.app.service
    ).
  • 构建工具: 使用Maven(
    pom.xml
    )或Gradle(
    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
    ,
    @Repository
    , and
    @Controller
    /
    @RestController
    annotations appropriately to define beans.
  • 构造函数注入: 对于必需的依赖项,始终使用基于构造函数的注入。这让组件更易于测试,且依赖关系更明确。
  • 不可变性: 将依赖字段声明为
    private final
  • 组件注解: 合理使用
    @Component
    @Service
    @Repository
    以及
    @Controller
    /
    @RestController
    注解来定义Bean。

Configuration

配置管理

  • Externalized Configuration: Use
    application.yml
    (or
    application.properties
    ) for configuration. YAML is often preferred for its readability and hierarchical structure.
  • Type-Safe Properties: Use
    @ConfigurationProperties
    to bind configuration to strongly-typed Java objects.
  • Profiles: Use Spring Profiles (
    application-dev.yml
    ,
    application-prod.yml
    ) to manage environment-specific configurations.
  • Secrets Management: Do not hardcode secrets. Use environment variables, or a dedicated secret management tool like HashiCorp Vault or AWS Secrets Manager.
  • 外部化配置: 使用
    application.yml
    (或
    application.properties
    )进行配置。YAML因其可读性和分层结构常被优先选择。
  • 类型安全属性: 使用
    @ConfigurationProperties
    将配置绑定到强类型Java对象。
  • 环境配置文件: 使用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
    ,
    @Size
    ) on DTOs to validate request payloads.
  • Error Handling: Implement a global exception handler using
    @ControllerAdvice
    and
    @ExceptionHandler
    to provide consistent error responses.
  • 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
    @Service
    classes.
  • Statelessness: Services should be stateless.
  • Transaction Management: Use
    @Transactional
    on service methods to manage database transactions declaratively. Apply it at the most granular level necessary.
  • 业务逻辑: 将所有业务逻辑封装在
    @Service
    类中。
  • 无状态: 服务应保持无状态。
  • 事务管理: 在服务方法上使用
    @Transactional
    声明式管理数据库事务。仅在必要的最细粒度级别上应用。

Data Layer (Repositories)

数据层(仓库)

  • Spring Data JPA: Use Spring Data JPA repositories by extending
    JpaRepository
    or
    CrudRepository
    for standard database operations.
  • Custom Queries: For complex queries, use
    @Query
    or the JPA Criteria API.
  • Projections: Use DTO projections to fetch only the necessary data from the database.
  • Spring Data JPA: 通过继承
    JpaRepository
    CrudRepository
    使用Spring Data JPA仓库执行标准数据库操作。
  • 自定义查询: 对于复杂查询,使用
    @Query
    或JPA Criteria API。
  • 投影查询: 使用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 (
    logger.info("Processing user {}...", userId);
    ) instead of string concatenation to improve performance.
  • 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
    @SpringBootTest
    for integration tests that load the Spring application context.
  • Test Slices: Use test slice annotations like
    @WebMvcTest
    (for controllers) or
    @DataJpaTest
    (for repositories) to test specific parts of the application in isolation.
  • Testcontainers: Consider using Testcontainers for reliable integration tests with real databases, message brokers, etc.
  • 单元测试: 使用JUnit 5和Mockito等模拟框架为服务和组件编写单元测试。
  • 集成测试: 使用
    @SpringBootTest
    加载Spring应用上下文进行集成测试。
  • 测试切片: 使用测试切片注解如
    @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)。