moai-lang-java
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseQuick Reference (30 seconds)
快速参考(30秒)
Java 21 LTS Expert - Enterprise development with Spring Boot 3.3, Virtual Threads, and modern Java features.
Auto-Triggers: Java files with .java extension, build files including pom.xml, build.gradle, or build.gradle.kts
Core Capabilities:
- Java 21 LTS: Virtual threads, pattern matching, record patterns, sealed classes
- Spring Boot 3.3: REST controllers, services, repositories, WebFlux reactive
- Spring Security 6: JWT authentication, OAuth2, role-based access control
- JPA/Hibernate 7: Entity mapping, relationships, queries, transactions
- JUnit 5: Unit testing, mocking, TestContainers integration
- Build Tools: Maven 3.9, Gradle 8.5 with Kotlin DSL
Java 21 LTS专家 - 基于Spring Boot 3.3、Virtual Threads和现代Java特性的企业级开发。
自动触发条件:.java扩展名的Java文件,以及pom.xml、build.gradle或build.gradle.kts等构建文件
核心能力:
- Java 21 LTS:Virtual Threads、模式匹配、记录模式、密封类
- Spring Boot 3.3:REST控制器、服务、仓库、WebFlux响应式编程
- Spring Security 6:JWT认证、OAuth2、基于角色的访问控制
- JPA/Hibernate 7:实体映射、关联关系、查询、事务
- JUnit 5:单元测试、Mocking、TestContainers集成
- 构建工具:Maven 3.9、带Kotlin DSL的Gradle 8.5
Implementation Guide (5 minutes)
实施指南(5分钟)
Java 21 LTS Features
Java 21 LTS特性
Virtual Threads with Project Loom:
Use try-with-resources on Executors.newVirtualThreadPerTaskExecutor. Call IntStream.range from 0 to 10000 and forEach to submit tasks that sleep for one second and return the iteration value.
Structured Concurrency Preview Pattern:
Use try-with-resources on new StructuredTaskScope.ShutdownOnFailure. Fork tasks for fetching user and orders by calling scope.fork with lambda expressions. Call scope.join then throwIfFailed. Return new composite object with results from both task suppliers.
Pattern Matching for Switch:
Create describe method taking Object parameter. Use switch expression with cases for Integer i with guard condition i greater than 0 returning positive integer message, Integer i returning non-positive message, String s returning length message, List with wildcard returning size message, null returning null value, and default returning unknown type.
Record Patterns and Sealed Classes:
Define Point record with int x and int y. Define Rectangle record with Point topLeft and Point bottomRight. Create area method that uses switch with Rectangle pattern destructuring both Point components into variables, returning absolute value of width times height. Define sealed Shape interface permitting Circle and Rectangle. Implement Circle record with area method using PI times radius squared.
基于Project Loom的Virtual Threads:
在Executors.newVirtualThreadPerTaskExecutor上使用try-with-resources语法。调用IntStream.range(0,10000)并通过forEach提交休眠1秒后返回迭代值的任务。
结构化并发预览模式:
在new StructuredTaskScope.ShutdownOnFailure上使用try-with-resources语法。通过调用scope.fork并传入lambda表达式,分叉获取用户和订单的任务。调用scope.join后再调用throwIfFailed。返回包含两个任务结果的新复合对象。
Switch语句的模式匹配:
创建一个接收Object参数的describe方法。使用switch表达式,包含以下分支:带有守卫条件i>0的Integer i分支,返回正整数消息;Integer i分支,返回非正整数消息;String s分支,返回长度消息;带通配符的List分支,返回大小消息;null分支,返回空值消息;default分支,返回未知类型消息。
记录模式与密封类:
定义包含int x和int y的Point记录。定义包含Point topLeft和Point bottomRight的Rectangle记录。创建area方法,使用switch语句结合Rectangle模式,解构两个Point组件到变量中,返回宽度乘以高度的绝对值。定义密封的Shape接口,允许Circle和Rectangle实现。实现带有area方法的Circle记录,使用PI乘以半径的平方计算面积。
Spring Boot 3.3
Spring Boot 3.3
REST Controller Pattern:
Create UserController with RestController annotation, RequestMapping for api/users, and RequiredArgsConstructor. Inject UserService. Create getUser method with GetMapping and PathVariable for id, returning ResponseEntity that maps findById result to ok or returns notFound. Create createUser method with PostMapping, Valid annotation, and RequestBody for CreateUserRequest. Create user, build URI location, return created response with body. Create deleteUser method with DeleteMapping that returns noContent or notFound based on service result.
Service Layer Pattern:
Create UserService with Service, RequiredArgsConstructor, and Transactional readOnly true annotations. Inject UserRepository and PasswordEncoder. Create findById method returning Optional. Create transactional create method that checks for duplicate email throwing DuplicateEmailException, builds User with builder pattern encoding password, and saves to repository.
REST控制器模式:
创建带有RestController注解、RequestMapping映射到/api/users的UserController,并使用RequiredArgsConstructor注解。注入UserService。创建带有GetMapping和PathVariable(id)的getUser方法,返回ResponseEntity,将findById的结果映射为ok响应或返回notFound。创建带有PostMapping、Valid注解和RequestBody(CreateUserRequest)的createUser方法。创建用户,构建URI位置,返回包含响应体的created响应。创建带有DeleteMapping的deleteUser方法,根据服务结果返回noContent或notFound。
服务层模式:
创建带有Service、RequiredArgsConstructor和Transactional(readOnly = true)注解的UserService。注入UserRepository和PasswordEncoder。创建返回Optional的findById方法。创建事务性的create方法,检查重复邮箱并抛出DuplicateEmailException,使用构建者模式构建User并加密密码,然后保存到仓库。
Spring Security 6
Spring Security 6
Security Configuration Pattern:
Create SecurityConfig with Configuration and EnableWebSecurity annotations. Define filterChain Bean taking HttpSecurity. Configure authorizeHttpRequests with permitAll for public API paths, hasRole ADMIN for admin paths, and authenticated for all other requests. Configure oauth2ResourceServer with jwt default. Set sessionManagement to STATELESS and disable csrf. Define passwordEncoder Bean returning BCryptPasswordEncoder.
安全配置模式:
创建带有Configuration和EnableWebSecurity注解的SecurityConfig。定义接收HttpSecurity的filterChain Bean。配置authorizeHttpRequests,允许所有公共API路径,管理员路径需要ADMIN角色,其他所有请求需要认证。配置oauth2ResourceServer使用默认jwt。设置sessionManagement为STATELESS并禁用csrf。定义返回BCryptPasswordEncoder的passwordEncoder Bean。
JPA/Hibernate Patterns
JPA/Hibernate模式
Entity Definition Pattern:
Create User entity with Entity and Table annotations. Add Lombok Getter, Setter, NoArgsConstructor, and Builder annotations. Define id with Id and GeneratedValue IDENTITY. Define name and email with Column nullable false, email also unique. Define status with Enumerated STRING. Define orders with OneToMany mappedBy user, cascade ALL, and orphanRemoval true.
Repository with Custom Queries Pattern:
Create UserRepository extending JpaRepository. Add findByEmail returning Optional. Add existsByEmail returning boolean. Add Query annotation for JPQL with LEFT JOIN FETCH for findByIdWithOrders using Param annotation. Add findByNameContainingIgnoreCase with Pageable for pagination.
DTOs as Records Pattern:
Create UserDto record with id, name, email, and status. Add static from factory method that constructs record from User entity. Create CreateUserRequest record with NotBlank and Size annotations for name, NotBlank and Email for email, NotBlank and Size min 8 for password.
实体定义模式:
创建带有Entity和Table注解的User实体。添加Lombok的Getter、Setter、NoArgsConstructor和Builder注解。使用Id和GeneratedValue(IDENTITY)定义id。使用Column(nullable = false)定义name和email,email同时设置为unique。使用Enumerated(STRING)定义status。使用OneToMany(mappedBy = "user", cascade = ALL, orphanRemoval = true)定义orders。
带自定义查询的仓库模式:
创建继承JpaRepository的UserRepository。添加返回Optional的findByEmail方法。添加返回boolean的existsByEmail方法。添加带有Query注解的JPQL查询,使用LEFT JOIN FETCH实现findByIdWithOrders,并使用Param注解。添加带有Pageable的findByNameContainingIgnoreCase方法以支持分页。
基于记录的DTO模式:
创建包含id、name、email和status的UserDto记录。添加静态from工厂方法,从User实体构建该记录。创建带有NotBlank和Size注解的name字段、NotBlank和Email注解的email字段、NotBlank和Size(min=8)注解的password字段的CreateUserRequest记录。
Advanced Patterns
高级模式
Virtual Threads Integration
Virtual Threads集成
Create AsyncUserService with Service and RequiredArgsConstructor annotations. Create fetchUserDetails method using StructuredTaskScope.ShutdownOnFailure in try-with-resources. Fork tasks for user and orders queries, join and throw if failed, return composite result. Create processUsersInParallel method using newVirtualThreadPerTaskExecutor and streaming user IDs to submit processing tasks.
创建带有Service和RequiredArgsConstructor注解的AsyncUserService。创建使用try-with-resources语法的StructuredTaskScope.ShutdownOnFailure的fetchUserDetails方法。分叉用户和订单查询的任务,调用join并在失败时抛出异常,返回复合结果。创建使用newVirtualThreadPerTaskExecutor并流式处理用户ID以提交处理任务的processUsersInParallel方法。
Build Configuration
构建配置
Maven 3.9 Pattern:
Define project with parent for spring-boot-starter-parent version 3.3.0. Set java.version property to 21. Add dependencies for spring-boot-starter-web and spring-boot-starter-data-jpa.
Gradle 8.5 Kotlin DSL Pattern:
Apply plugins for org.springframework.boot, io.spring.dependency-management, and java. Set toolchain languageVersion to 21. Add implementation dependencies for web and data-jpa starters, testImplementation for test starter.
Maven 3.9模式:
定义父项目为spring-boot-starter-parent 3.3.0版本。设置java.version属性为21。添加spring-boot-starter-web和spring-boot-starter-data-jpa依赖。
Gradle 8.5 Kotlin DSL模式:
应用org.springframework.boot、io.spring.dependency-management和java插件。设置toolchain的languageVersion为21。添加web和data-jpa starter的implementation依赖,以及test starter的testImplementation依赖。
Testing with JUnit 5
基于JUnit 5的测试
Unit Testing Pattern:
Create test class with ExtendWith MockitoExtension. Add Mock annotation for UserRepository. Add InjectMocks for UserService. Create shouldCreateUser test that stubs existsByEmail to return false and save to return user with id. Call service create and assertThat result id equals 1.
Integration Testing with TestContainers Pattern:
Create test class with Testcontainers and SpringBootTest annotations. Define static Container for PostgreSQL with postgres:16-alpine image. Add DynamicPropertySource to set datasource.url from container. Autowire repository. Create test that saves user and assertThat id isNotNull.
单元测试模式:
创建带有ExtendWith(MockitoExtension.class)注解的测试类。添加@Mock注解的UserRepository。添加@InjectMocks注解的UserService。创建shouldCreateUser测试方法,stub existsByEmail返回false,save返回id为1的user。调用service的create方法,断言结果的id等于1。
基于TestContainers的集成测试模式:
创建带有@Testcontainers和@SpringBootTest注解的测试类。定义静态的PostgreSQL容器,使用postgres:16-alpine镜像。添加DynamicPropertySource以从容器设置datasource.url。自动装配repository。创建保存用户并断言id不为null的测试方法。
Context7 Integration
Context7集成
Library mappings for latest documentation:
- spring-projects/spring-boot for Spring Boot 3.3 documentation
- spring-projects/spring-framework for Spring Framework core
- spring-projects/spring-security for Spring Security 6
- hibernate/hibernate-orm for Hibernate 7 ORM patterns
- junit-team/junit5 for JUnit 5 testing framework
最新文档的库映射:
- spring-projects/spring-boot:Spring Boot 3.3文档
- spring-projects/spring-framework:Spring Framework核心文档
- spring-projects/spring-security:Spring Security 6文档
- hibernate/hibernate-orm:Hibernate 7 ORM模式文档
- junit-team/junit5:JUnit 5测试框架文档
Works Well With
适配工具
- moai-lang-kotlin for Kotlin interoperability and Spring Kotlin extensions
- moai-domain-backend for REST API, GraphQL, and microservices architecture
- moai-domain-database for JPA, Hibernate, and R2DBC patterns
- moai-foundation-quality for JUnit 5, Mockito, and TestContainers integration
- moai-infra-docker for JVM container optimization
- moai-lang-kotlin:Kotlin互操作性及Spring Kotlin扩展
- moai-domain-backend:REST API、GraphQL和微服务架构
- moai-domain-database:JPA、Hibernate和R2DBC模式
- moai-foundation-quality:JUnit 5、Mockito和TestContainers集成
- moai-infra-docker:JVM容器优化
Troubleshooting
故障排除
Common Issues:
- Version mismatch: Run java -version and check JAVA_HOME points to Java 21
- Compilation errors: Run mvn clean compile -X or gradle build --info
- Virtual thread issues: Ensure Java 21+ with --enable-preview if needed
- JPA lazy loading: Use Transactional annotation or JOIN FETCH queries
Performance Tips:
- Enable Virtual Threads by setting spring.threads.virtual.enabled to true
- Use GraalVM Native Image for faster startup
- Configure connection pooling with HikariCP
常见问题:
- 版本不匹配:运行java -version并检查JAVA_HOME指向Java 21
- 编译错误:运行mvn clean compile -X或gradle build --info
- Virtual Threads问题:确保使用Java 21+,必要时添加--enable-preview参数
- JPA懒加载:使用Transactional注解或JOIN FETCH查询
性能优化建议:
- 通过设置spring.threads.virtual.enabled为true启用Virtual Threads
- 使用GraalVM Native Image实现更快启动
- 配置HikariCP连接池
Advanced Documentation
高级文档
For comprehensive reference materials:
- reference.md for Java 21 features, Context7 mappings, and performance
- examples.md for production-ready Spring Boot examples
Last Updated: 2026-01-11
Status: Production Ready (v1.1.0)
如需全面参考资料:
- reference.md:Java 21特性、Context7映射及性能优化
- examples.md:生产级Spring Boot示例
最后更新:2026-01-11
状态:生产就绪(v1.1.0)