spring-boot
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSpring 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 , , and . Every instruction prioritizes type safety, minimal configuration, and secure-by-default behavior.
@SpringBootTestMockMvcWebTestClient指导使用Java 21+特性(records、密封类、虚拟线程)、带lambda DSL的Spring Security 6、带查询推导和投影的Spring Data JPA、响应式WebFlux端点,以及结合、和的全面测试,来设计和实现生产级Spring Boot 3.4+应用程序。所有指令都优先考虑类型安全、最小化配置和默认安全的行为。
@SpringBootTestMockMvcWebTestClientWhen 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 /
Monoreturn types.Flux - 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
操作指南
-
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 usingimports and the deprecated
javax.*will not compile.WebSecurityConfigurerAdapter -
Use Java records for DTOs, request bodies, and response payloads because records are immutable by construction, generate/
equals/hashCodeautomatically, and signal to reviewers that the type carries data without behavior.toString -
Defineclasses with constructor injection and avoid field injection with
@RestControllerbecause constructor injection makes dependencies explicit, enables final fields, and allows instantiation in tests without a Spring context.@Autowired -
Organize the application into feature packages with,
@Service, and@Repositorystereotypes because component scanning respects package boundaries, and cross-package access should go through explicit@Controllerconfiguration rather than implicit scanning.@Bean -
Use Spring Data JPA repository interfaces with derived query methods andfor complex cases because derived queries are compile-time verified against the entity model, and JPQL
@Querymethods surface syntax errors at startup rather than at call time.@Query -
Applyon service methods that perform multiple writes and configure
@Transactionalfor read-only transactions because missing transaction boundaries cause partial writes on failure, andreadOnly = trueenables Hibernate flush-mode optimizations that reduce query overhead.readOnly -
Configure Spring Security 6 with thebean and lambda DSL instead of extending
SecurityFilterChainbecause the adapter was removed in Spring Security 6, and the lambda DSL produces a more readable, composable filter chain configuration.WebSecurityConfigurerAdapter -
Useand
@PreAuthorizewith 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.@PostAuthorize -
Enable virtual threads withfor 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.
spring.threads.virtual.enabled=true -
Usefor non-blocking HTTP calls and
WebClientfor synchronous calls in virtual-thread contexts becauseRestClientis in maintenance mode,RestTemplateintegrates with the reactive pipeline, andWebClientprovides a modern fluent API for imperative code.RestClient -
Build reactive endpoints withreturning
@RestControllerandMono<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.Flux<T> -
Write entity classes with,
@Entity, and explicit@Idmappings, and mark lazy associations with@Columnbecause Hibernate defaults@ManyToOne(fetch = LAZY)to@ManyToOne, which silently triggers N+1 queries that dominate response time in list endpoints.EAGER -
Usefor repository tests and
@DataJpaTestfor 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.@WebMvcTest -
Write integration tests withand
@SpringBootTestfor 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.@Testcontainers -
Externalize configuration withbound to a record and validated with
@ConfigurationPropertiesbecause@Validatedinjection scatters configuration across the codebase, lacks validation, and cannot be tested without a running Spring context.@Value -
Configure structured logging with, 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.
spring.application.name
-
生成代码前确认Spring Boot版本和Java基准版本:Spring Boot 3.4要求Java 17+,默认使用Jakarta EE 10命名空间,而Spring Boot 2.x中使用导入和已弃用的
javax.*的代码模式将无法编译。WebSecurityConfigurerAdapter -
将Java records用于DTO、请求体和响应负载:records天生不可变,会自动生成/
equals/hashCode方法,同时向代码审核者表明该类型仅承载数据而无业务行为。toString -
定义类时使用构造函数注入,避免使用
@RestController进行字段注入:构造函数注入使依赖关系明确,支持final字段,并且允许在测试中无需Spring上下文即可实例化类。@Autowired -
将应用按功能包组织,使用、
@Service和@Repository注解:组件扫描会遵循包边界,跨包访问应通过显式的@Controller配置实现,而非隐式扫描。@Bean -
使用带有派生查询方法的Spring Data JPA仓库接口,复杂场景下使用:派生查询会在编译时针对实体模型进行验证,而JPQL的
@Query方法会在启动时暴露语法错误,而非调用时。@Query -
在执行多次写入操作的服务方法上应用,并为只读事务配置
@Transactional:缺失事务边界会导致失败时出现部分写入,而readOnly = true可启用Hibernate刷新模式优化,减少查询开销。readOnly -
使用Bean和lambda DSL配置Spring Security 6,而非继承
SecurityFilterChain:该适配器在Spring Security 6中已被移除,lambda DSL能生成更具可读性、可组合的过滤器链配置。WebSecurityConfigurerAdapter -
结合SpEL表达式使用和
@PreAuthorize实现方法级授权:过滤器链中的URL模式匹配无法表达“只有资源所有者才能更新该实体”这类领域级规则,而方法安全会在参数解析后进行评估。@PostAuthorize -
为阻塞I/O工作负载启用虚拟线程,设置:虚拟线程通过将数百万轻量级线程多路复用到少量载体线程池上,消除了“每个请求一个线程”的瓶颈,显著提升数据库和HTTP客户端调用的吞吐量。
spring.threads.virtual.enabled=true -
非阻塞HTTP调用使用,虚拟线程上下文同步调用使用
WebClient:RestClient已进入维护模式,RestTemplate与响应式管道集成,WebClient为命令式代码提供了现代流畅API。RestClient -
当整个调用链为非阻塞时,使用返回和
Mono<T>的Flux<T>构建响应式端点:在响应式管道中混合阻塞调用会耗尽有限的Netty事件循环线程,其吞吐量甚至不如基于Servlet的方案。@RestController -
使用、
@Entity和显式@Id映射编写实体类,并用@Column标记延迟关联:Hibernate默认@ManyToOne(fetch = LAZY)为@ManyToOne,这会静默触发N+1查询,在列表端点中成为响应时间的主要影响因素。EAGER -
使用进行仓库测试,
@DataJpaTest进行控制器测试,避免加载完整应用上下文:切片测试可在两秒内启动,隔离被测层,并仅自动配置相关Bean。@WebMvcTest -
使用和
@SpringBootTest编写依赖数据库的集成测试:内存数据库H2在JSON列、窗口函数和锁等方面与PostgreSQL/MySQL行为存在差异,Testcontainers提供真实数据库且无需手动配置。@Testcontainers -
使用绑定到record的进行外部化配置,并通过
@ConfigurationProperties验证:@Validated注入会将配置分散在代码库中,缺乏验证,且无需运行Spring上下文即可测试。@Value -
为生产环境配置结构化日志,包含、关联ID和JSON输出:非结构化文本日志无法被可观测性平台解析,而关联ID是跨微服务边界追踪请求的必需项。
spring.application.name
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 only when the task needs live browser evidence against a Spring-backed UI surface.
../web-testing/SKILL.md
- 将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 and . When generating controllers, always show the record DTOs, service interface, and security configuration alongside the endpoint.
src/main/java/src/test/java/根据需求提供实现代码、配置属性、Bean定义和架构指导。包含相对于和的文件路径。生成控制器时,始终附带record DTO、服务接口和安全配置。
src/main/java/src/test/java/References
参考资料
| File | Load when |
|---|---|
| You need bean scoping, |
| You need Spring Security 6 filter chain configuration, JWT authentication, method security, or CORS setup. |
| You need Spring Data JPA repositories, query derivation, projections, specifications, or Hibernate tuning. |
| You need |
| You need WebFlux endpoints, |
| 文件 | 加载时机 |
|---|---|
| 需要Bean作用域、 |
| 需要Spring Security 6过滤器链配置、JWT认证、方法安全或CORS设置时。 |
| 需要Spring Data JPA仓库、查询推导、投影、规格或Hibernate调优时。 |
| 需要 |
| 需要WebFlux端点、 |