spring-boot

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Spring Boot

Spring Boot

Purpose

用途

Guide the design and implementation of production-grade Spring Boot 3.4+ applications using Java 21+ features (records, sealed classes, virtual threads), Spring Security 6 with the lambda DSL, Spring Data JPA with query derivation and projections, reactive WebFlux endpoints, and comprehensive testing with
@SpringBootTest
,
MockMvc
, and
WebTestClient
. Every instruction prioritizes type safety, minimal configuration, and secure-by-default behavior.
指导使用Java 21+特性(records、密封类、虚拟线程)、带lambda DSL的Spring Security 6、带查询推导和投影的Spring Data JPA、响应式WebFlux端点,以及结合
@SpringBootTest
MockMvc
WebTestClient
的全面测试,来设计和实现生产级Spring Boot 3.4+应用程序。所有指令都优先考虑类型安全、最小化配置和默认安全的行为。

When to Use

适用场景

  • Scaffolding a new Spring Boot application or adding feature modules to an existing one.
  • Designing REST controllers, service layers, and repository interfaces with Spring Data JPA.
  • Implementing authentication and authorization with Spring Security 6 filter chains and method security.
  • Building reactive endpoints with WebFlux and
    Mono
    /
    Flux
    return types.
  • Configuring virtual threads for high-concurrency blocking I/O workloads.
  • Reviewing Spring Boot code for security misconfigurations, N+1 queries, or bean scope issues.
  • 搭建新的Spring Boot应用程序,或为现有应用添加功能模块。
  • 使用Spring Data JPA设计REST控制器、服务层和仓库接口。
  • 使用Spring Security 6过滤器链和方法安全实现认证与授权。
  • 使用WebFlux和
    Mono
    /
    Flux
    返回类型构建响应式端点。
  • 为高并发阻塞I/O工作负载配置虚拟线程。
  • 检查Spring Boot代码中的安全配置错误、N+1查询或Bean作用域问题。

Instructions

操作指南

  1. Confirm the Spring Boot version and Java baseline before generating code because Spring Boot 3.4 requires Java 17+ and defaults to Jakarta EE 10 namespaces, and patterns from Spring Boot 2.x using
    javax.*
    imports and the deprecated
    WebSecurityConfigurerAdapter
    will not compile.
  2. Use Java records for DTOs, request bodies, and response payloads because records are immutable by construction, generate
    equals
    /
    hashCode
    /
    toString
    automatically, and signal to reviewers that the type carries data without behavior.
  3. Define
    @RestController
    classes with constructor injection and avoid field injection with
    @Autowired
    because constructor injection makes dependencies explicit, enables final fields, and allows instantiation in tests without a Spring context.
  4. Organize the application into feature packages with
    @Service
    ,
    @Repository
    , and
    @Controller
    stereotypes
    because component scanning respects package boundaries, and cross-package access should go through explicit
    @Bean
    configuration rather than implicit scanning.
  5. Use Spring Data JPA repository interfaces with derived query methods and
    @Query
    for complex cases
    because derived queries are compile-time verified against the entity model, and JPQL
    @Query
    methods surface syntax errors at startup rather than at call time.
  6. Apply
    @Transactional
    on service methods that perform multiple writes and configure
    readOnly = true
    for read-only transactions
    because missing transaction boundaries cause partial writes on failure, and
    readOnly
    enables Hibernate flush-mode optimizations that reduce query overhead.
  7. Configure Spring Security 6 with the
    SecurityFilterChain
    bean and lambda DSL instead of extending
    WebSecurityConfigurerAdapter
    because the adapter was removed in Spring Security 6, and the lambda DSL produces a more readable, composable filter chain configuration.
  8. Use
    @PreAuthorize
    and
    @PostAuthorize
    with SpEL expressions for method-level authorization
    because URL-pattern matching in the filter chain cannot express domain-level rules like "only the resource owner can update this entity," and method security evaluates after the arguments are resolved.
  9. Enable virtual threads with
    spring.threads.virtual.enabled=true
    for blocking I/O workloads
    because virtual threads eliminate the thread-per-request bottleneck by multiplexing millions of lightweight threads onto a small carrier pool, dramatically improving throughput for database and HTTP client calls.
  10. Use
    WebClient
    for non-blocking HTTP calls and
    RestClient
    for synchronous calls in virtual-thread contexts
    because
    RestTemplate
    is in maintenance mode,
    WebClient
    integrates with the reactive pipeline, and
    RestClient
    provides a modern fluent API for imperative code.
  11. Build reactive endpoints with
    @RestController
    returning
    Mono<T>
    and
    Flux<T>
    when the entire call chain is non-blocking
    because mixing blocking calls inside a reactive pipeline exhausts the limited Netty event-loop threads and produces worse throughput than a servlet-based approach.
  12. Write entity classes with
    @Entity
    ,
    @Id
    , and explicit
    @Column
    mappings, and mark lazy associations with
    @ManyToOne(fetch = LAZY)
    because Hibernate defaults
    @ManyToOne
    to
    EAGER
    , which silently triggers N+1 queries that dominate response time in list endpoints.
  13. Use
    @DataJpaTest
    for repository tests and
    @WebMvcTest
    for controller tests to avoid loading the full application context
    because slice tests start in under two seconds, isolate the layer under test, and auto-configure only the relevant beans.
  14. Write integration tests with
    @SpringBootTest
    and
    @Testcontainers
    for database-dependent tests
    because in-memory H2 diverges from PostgreSQL/MySQL behavior in areas like JSON columns, window functions, and locking, and Testcontainers provides a real database with zero manual setup.
  15. Externalize configuration with
    @ConfigurationProperties
    bound to a record and validated with
    @Validated
    because
    @Value
    injection scatters configuration across the codebase, lacks validation, and cannot be tested without a running Spring context.
  16. Configure structured logging with
    spring.application.name
    , correlation IDs, and JSON output for production
    because unstructured text logs are unparseable by observability platforms, and correlation IDs are required to trace requests across microservice boundaries.
  1. 生成代码前确认Spring Boot版本和Java基准版本:Spring Boot 3.4要求Java 17+,默认使用Jakarta EE 10命名空间,而Spring Boot 2.x中使用
    javax.*
    导入和已弃用的
    WebSecurityConfigurerAdapter
    的代码模式将无法编译。
  2. 将Java records用于DTO、请求体和响应负载:records天生不可变,会自动生成
    equals
    /
    hashCode
    /
    toString
    方法,同时向代码审核者表明该类型仅承载数据而无业务行为。
  3. 定义
    @RestController
    类时使用构造函数注入,避免使用
    @Autowired
    进行字段注入
    :构造函数注入使依赖关系明确,支持final字段,并且允许在测试中无需Spring上下文即可实例化类。
  4. 将应用按功能包组织,使用
    @Service
    @Repository
    @Controller
    注解
    :组件扫描会遵循包边界,跨包访问应通过显式的
    @Bean
    配置实现,而非隐式扫描。
  5. 使用带有派生查询方法的Spring Data JPA仓库接口,复杂场景下使用
    @Query
    :派生查询会在编译时针对实体模型进行验证,而JPQL的
    @Query
    方法会在启动时暴露语法错误,而非调用时。
  6. 在执行多次写入操作的服务方法上应用
    @Transactional
    ,并为只读事务配置
    readOnly = true
    :缺失事务边界会导致失败时出现部分写入,而
    readOnly
    可启用Hibernate刷新模式优化,减少查询开销。
  7. 使用
    SecurityFilterChain
    Bean和lambda DSL配置Spring Security 6,而非继承
    WebSecurityConfigurerAdapter
    :该适配器在Spring Security 6中已被移除,lambda DSL能生成更具可读性、可组合的过滤器链配置。
  8. 结合SpEL表达式使用
    @PreAuthorize
    @PostAuthorize
    实现方法级授权
    :过滤器链中的URL模式匹配无法表达“只有资源所有者才能更新该实体”这类领域级规则,而方法安全会在参数解析后进行评估。
  9. 为阻塞I/O工作负载启用虚拟线程,设置
    spring.threads.virtual.enabled=true
    :虚拟线程通过将数百万轻量级线程多路复用到少量载体线程池上,消除了“每个请求一个线程”的瓶颈,显著提升数据库和HTTP客户端调用的吞吐量。
  10. 非阻塞HTTP调用使用
    WebClient
    ,虚拟线程上下文同步调用使用
    RestClient
    RestTemplate
    已进入维护模式,
    WebClient
    与响应式管道集成,
    RestClient
    为命令式代码提供了现代流畅API。
  11. 当整个调用链为非阻塞时,使用返回
    Mono<T>
    Flux<T>
    @RestController
    构建响应式端点
    :在响应式管道中混合阻塞调用会耗尽有限的Netty事件循环线程,其吞吐量甚至不如基于Servlet的方案。
  12. 使用
    @Entity
    @Id
    和显式
    @Column
    映射编写实体类,并用
    @ManyToOne(fetch = LAZY)
    标记延迟关联
    :Hibernate默认
    @ManyToOne
    EAGER
    ,这会静默触发N+1查询,在列表端点中成为响应时间的主要影响因素。
  13. 使用
    @DataJpaTest
    进行仓库测试,
    @WebMvcTest
    进行控制器测试,避免加载完整应用上下文
    :切片测试可在两秒内启动,隔离被测层,并仅自动配置相关Bean。
  14. 使用
    @SpringBootTest
    @Testcontainers
    编写依赖数据库的集成测试
    :内存数据库H2在JSON列、窗口函数和锁等方面与PostgreSQL/MySQL行为存在差异,Testcontainers提供真实数据库且无需手动配置。
  15. 使用绑定到record的
    @ConfigurationProperties
    进行外部化配置,并通过
    @Validated
    验证
    @Value
    注入会将配置分散在代码库中,缺乏验证,且无需运行Spring上下文即可测试。
  16. 为生产环境配置结构化日志,包含
    spring.application.name
    、关联ID和JSON输出
    :非结构化文本日志无法被可观测性平台解析,而关联ID是跨微服务边界追踪请求的必需项。

Testing Guidance

测试指导

  • Keep Spring Boot slice and runtime-boundary tests in this skill instead of routing new work through a separate generic runtime-testing skill.
  • Own application-context startup, slice tests, HTTP boundary checks, persistence fixtures, and container-backed integration setup here because they are Spring-runtime concerns.
  • Use the owning Java or Kotlin skill for narrow unit tests that do not need the Spring runtime boundary.
  • Use
    ../web-testing/SKILL.md
    only when the task needs live browser evidence against a Spring-backed UI surface.
  • 将Spring Boot切片测试和运行时边界测试保留在本技能中,而非通过单独的通用运行时测试技能处理新任务。
  • 负责应用上下文启动、切片测试、HTTP边界检查、持久化测试夹具和容器支持的集成设置,因为这些属于Spring运行时相关事项。
  • 不需要Spring运行时边界的窄范围单元测试,请使用对应的Java或Kotlin技能。
  • 只有当任务需要针对Spring后端UI界面获取实时浏览器证据时,才使用
    ../web-testing/SKILL.md

Output Format

输出格式

Provide implementation code, configuration properties, bean definitions, and architectural guidance as appropriate. Include file paths relative to
src/main/java/
and
src/test/java/
. When generating controllers, always show the record DTOs, service interface, and security configuration alongside the endpoint.
根据需求提供实现代码、配置属性、Bean定义和架构指导。包含相对于
src/main/java/
src/test/java/
的文件路径。生成控制器时,始终附带record DTO、服务接口和安全配置。

References

参考资料

FileLoad when
references/dependency-injection.md
You need bean scoping,
@ConfigurationProperties
, profiles, conditional beans, or constructor injection patterns.
references/security.md
You need Spring Security 6 filter chain configuration, JWT authentication, method security, or CORS setup.
references/data-access.md
You need Spring Data JPA repositories, query derivation, projections, specifications, or Hibernate tuning.
references/testing.md
You need
@SpringBootTest
,
@WebMvcTest
,
@DataJpaTest
, Testcontainers, or
MockMvc
/
WebTestClient
patterns.
references/reactive.md
You need WebFlux endpoints,
Mono
/
Flux
patterns,
WebClient
, R2DBC, or reactive security configuration.
文件加载时机
references/dependency-injection.md
需要Bean作用域、
@ConfigurationProperties
、配置文件、条件Bean或构造函数注入模式时。
references/security.md
需要Spring Security 6过滤器链配置、JWT认证、方法安全或CORS设置时。
references/data-access.md
需要Spring Data JPA仓库、查询推导、投影、规格或Hibernate调优时。
references/testing.md
需要
@SpringBootTest
@WebMvcTest
@DataJpaTest
、Testcontainers或
MockMvc
/
WebTestClient
模式时。
references/reactive.md
需要WebFlux端点、
Mono
/
Flux
模式、
WebClient
、R2DBC或响应式安全配置时。