kotlin-springboot
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSpring 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 () or Gradle (
pom.xml) with the Kotlin plugins (build.gradleorkotlin-maven-plugin).org.jetbrains.kotlin.jvm - Kotlin Plugins: For JPA, enable the plugin to automatically make entity classes
kotlin-jpawithout boilerplate.open - Starters: Use Spring Boot starters (e.g., ,
spring-boot-starter-web) as usual.spring-boot-starter-data-jpa - Package Structure: Organize code by feature/domain (e.g., ,
com.example.app.order) rather than by layer.com.example.app.user
- 构建工具: 使用Maven()或Gradle(
pom.xml)并搭配Kotlin插件(build.gradle或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 in the primary constructor. Prefer
private valovervaleverywhere to promote immutability.var - Component Stereotypes: Use ,
@Service, and@Repositoryannotations just as you would in Java.@RestController
- 主构造函数: 始终使用主构造函数进行必要的依赖注入。这是Kotlin中最符合语言习惯且简洁的方式。
- 不可变性: 在主构造函数中将依赖声明为。在所有场景下优先使用
private val而非val,以提升不可变性。var - 组件 stereotype 注解: 像在Java中一样使用、
@Service和@Repository注解。@RestController
Configuration
配置
- Externalized Configuration: Use for its readability and hierarchical structure.
application.yml - Type-Safe Properties: Use with
@ConfigurationPropertiesto create immutable, type-safe configuration objects.data class - Profiles: Use Spring Profiles (,
application-dev.yml) to manage environment-specific configurations.application-prod.yml - 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 for all DTOs. This provides
data class,equals(),hashCode(), andtoString()for free and promotes immutability.copy() - Validation: Use Java Bean Validation (JSR 380) with annotations (,
@Valid,@NotNull) on your DTO data classes.@Size - Error Handling: Implement a global exception handler using and
@ControllerAdvicefor consistent error responses.@ExceptionHandler
- 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 classes.
@Service - Statelessness: Services should be stateless.
- Transaction Management: Use on service methods. In Kotlin, this can be applied to class or function level.
@Transactional
- 业务逻辑: 将业务逻辑封装在类中。
@Service - 无状态: 服务应保持无状态。
- 事务管理: 在服务方法上使用注解。在Kotlin中,这可以应用于类或函数级别。
@Transactional
Data Layer (Repositories)
数据层(仓库)
- JPA Entities: Define entities as classes. Remember they must be . It's highly recommended to use the
opencompiler plugin to handle this automatically.kotlin-jpa - 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 or
JpaRepository.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来使用Spring Data JPA仓库。CrudRepository - 协程: 对于响应式应用,在数据层利用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 () for performance and clarity.
logger.info("Processing user {}...", userId)
- 伴生对象日志器: 符合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 or
@WebMvcTestto test specific parts of the application.@DataJpaTest - 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
协程与异步编程
- functions: For non-blocking asynchronous code, use
suspendfunctions in your controllers and services. Spring Boot has excellent support for coroutines.suspend - Structured Concurrency: Use or
coroutineScopeto manage the lifecycle of coroutines.supervisorScope
- 函数: 对于非阻塞异步代码,在控制器和服务中使用
suspend函数。Spring Boot对协程有出色的支持。suspend - 结构化并发: 使用或
coroutineScope管理协程的生命周期。supervisorScope