kotlin-springboot

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Spring Boot with Kotlin Best Practices

Spring Boot 结合 Kotlin 开发最佳实践

Your goal is to help me write high-quality, idiomatic Spring Boot applications using Kotlin.
你的目标是帮助我编写高质量、符合Kotlin语言习惯的Spring Boot应用程序。

Project Setup & Structure

项目设置与结构

  • Build Tool: Use Maven (
    pom.xml
    ) or Gradle (
    build.gradle
    ) with the Kotlin plugins (
    kotlin-maven-plugin
    or
    org.jetbrains.kotlin.jvm
    ).
  • Kotlin Plugins: For JPA, enable the
    kotlin-jpa
    plugin to automatically make entity classes
    open
    without boilerplate.
  • Starters: Use Spring Boot starters (e.g.,
    spring-boot-starter-web
    ,
    spring-boot-starter-data-jpa
    ) as usual.
  • Package Structure: Organize code by feature/domain (e.g.,
    com.example.app.order
    ,
    com.example.app.user
    ) rather than by layer.
  • 构建工具: 使用Maven(
    pom.xml
    )或Gradle(
    build.gradle
    )并搭配Kotlin插件(
    kotlin-maven-plugin
    org.jetbrains.kotlin.jvm
    )。
  • Kotlin插件: 对于JPA,启用
    kotlin-jpa
    插件,无需样板代码即可自动将实体类设为
    open
  • Starter依赖: 照常使用Spring Boot Starter依赖(例如
    spring-boot-starter-web
    spring-boot-starter-data-jpa
    )。
  • 包结构: 按功能/领域组织代码(例如
    com.example.app.order
    com.example.app.user
    ),而非按分层结构。

Dependency Injection & Components

依赖注入与组件

  • Primary Constructors: Always use the primary constructor for required dependency injection. It's the most idiomatic and concise approach in Kotlin.
  • Immutability: Declare dependencies as
    private val
    in the primary constructor. Prefer
    val
    over
    var
    everywhere to promote immutability.
  • Component Stereotypes: Use
    @Service
    ,
    @Repository
    , and
    @RestController
    annotations just as you would in Java.
  • 主构造函数: 始终使用主构造函数进行必要的依赖注入。这是Kotlin中最符合语言习惯且简洁的方式。
  • 不可变性: 在主构造函数中将依赖声明为
    private val
    。在所有场景下优先使用
    val
    而非
    var
    ,以提升不可变性。
  • 组件 stereotype 注解: 像在Java中一样使用
    @Service
    @Repository
    @RestController
    注解。

Configuration

配置

  • Externalized Configuration: Use
    application.yml
    for its readability and hierarchical structure.
  • Type-Safe Properties: Use
    @ConfigurationProperties
    with
    data class
    to create immutable, type-safe configuration objects.
  • Profiles: Use Spring Profiles (
    application-dev.yml
    ,
    application-prod.yml
    ) to manage environment-specific configurations.
  • Secrets Management: Never hardcode secrets. Use environment variables or a dedicated secret management tool like HashiCorp Vault or AWS Secrets Manager.
  • 外部化配置: 使用
    application.yml
    ,因其可读性强且支持层级结构。
  • 类型安全属性: 结合
    @ConfigurationProperties
    data class
    创建不可变的类型安全配置对象。
  • 配置文件: 使用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.
  • Data Classes for DTOs: Use Kotlin
    data class
    for all DTOs. This provides
    equals()
    ,
    hashCode()
    ,
    toString()
    , and
    copy()
    for free and promotes immutability.
  • Validation: Use Java Bean Validation (JSR 380) with annotations (
    @Valid
    ,
    @NotNull
    ,
    @Size
    ) on your DTO data classes.
  • Error Handling: Implement a global exception handler using
    @ControllerAdvice
    and
    @ExceptionHandler
    for consistent error responses.
  • RESTful API: 设计清晰且一致的RESTful端点。
  • DTO使用数据类: 为所有DTO使用Kotlin
    data class
    。这会自动生成
    equals()
    hashCode()
    toString()
    copy()
    方法,并提升不可变性。
  • 验证: 在DTO数据类上使用Java Bean Validation(JSR 380)注解(
    @Valid
    @NotNull
    @Size
    )。
  • 错误处理: 使用
    @ControllerAdvice
    @ExceptionHandler
    实现全局异常处理器,以提供一致的错误响应。

Service Layer

服务层

  • Business Logic: Encapsulate business logic within
    @Service
    classes.
  • Statelessness: Services should be stateless.
  • Transaction Management: Use
    @Transactional
    on service methods. In Kotlin, this can be applied to class or function level.
  • 业务逻辑: 将业务逻辑封装在
    @Service
    类中。
  • 无状态: 服务应保持无状态。
  • 事务管理: 在服务方法上使用
    @Transactional
    注解。在Kotlin中,这可以应用于类或函数级别。

Data Layer (Repositories)

数据层(仓库)

  • JPA Entities: Define entities as classes. Remember they must be
    open
    . It's highly recommended to use the
    kotlin-jpa
    compiler plugin to handle this automatically.
  • Null Safety: Leverage Kotlin's null-safety (
    ?
    ) to clearly define which entity fields are optional or required at the type level.
  • Spring Data JPA: Use Spring Data JPA repositories by extending
    JpaRepository
    or
    CrudRepository
    .
  • Coroutines: For reactive applications, leverage Spring Boot's support for Kotlin Coroutines in the data layer.
  • JPA实体: 将实体定义为类。注意它们必须是
    open
    的。强烈建议使用
    kotlin-jpa
    编译器插件自动处理这一点。
  • 空安全: 利用Kotlin的空安全特性(
    ?
    ),在类型层面明确哪些实体字段是可选的或必填的。
  • Spring Data JPA: 通过继承
    JpaRepository
    CrudRepository
    来使用Spring Data JPA仓库。
  • 协程: 对于响应式应用,在数据层利用Spring Boot对Kotlin协程的支持。

Logging

日志

  • Companion Object Logger: The idiomatic way to declare a logger is in a companion object.
    kotlin
    companion object {
        private val logger = LoggerFactory.getLogger(MyClass::class.java)
    }
  • Parameterized Logging: Use parameterized messages (
    logger.info("Processing user {}...", userId)
    ) for performance and clarity.
  • 伴生对象日志器: 符合Kotlin语言习惯的日志器声明方式是在伴生对象中定义。
    kotlin
    companion object {
        private val logger = LoggerFactory.getLogger(MyClass::class.java)
    }
  • 参数化日志: 使用参数化消息(
    logger.info("Processing user {}...", userId)
    )以提升性能和可读性。

Testing

测试

  • JUnit 5: JUnit 5 is the default and works seamlessly with Kotlin.
  • Idiomatic Testing Libraries: For more fluent and idiomatic tests, consider using Kotest for assertions and MockK for mocking. They are designed for Kotlin and offer a more expressive syntax.
  • Test Slices: Use test slice annotations like
    @WebMvcTest
    or
    @DataJpaTest
    to test specific parts of the application.
  • Testcontainers: Use Testcontainers for reliable integration tests with real databases, message brokers, etc.
  • JUnit 5: JUnit 5是默认测试框架,与Kotlin无缝配合。
  • 符合Kotlin习惯的测试库: 为了编写更流畅、符合语言习惯的测试,考虑使用Kotest进行断言,使用MockK进行模拟。它们专为Kotlin设计,提供更具表现力的语法。
  • 测试切片: 使用测试切片注解,如
    @WebMvcTest
    @DataJpaTest
    ,来测试应用程序的特定部分。
  • Testcontainers: 使用Testcontainers进行可靠的集成测试,搭配真实的数据库、消息代理等。

Coroutines & Asynchronous Programming

协程与异步编程

  • suspend
    functions:
    For non-blocking asynchronous code, use
    suspend
    functions in your controllers and services. Spring Boot has excellent support for coroutines.
  • Structured Concurrency: Use
    coroutineScope
    or
    supervisorScope
    to manage the lifecycle of coroutines.
  • suspend
    函数:
    对于非阻塞异步代码,在控制器和服务中使用
    suspend
    函数。Spring Boot对协程有出色的支持。
  • 结构化并发: 使用
    coroutineScope
    supervisorScope
    管理协程的生命周期。