moai-lang-java by modu-ai/moai-adk
npx skills add https://github.com/modu-ai/moai-adk --skill moai-lang-javaJava 21 LTS 专家 - 使用 Spring Boot 3.3、虚拟线程和现代 Java 特性进行企业级开发。
自动触发:扩展名为 .java 的 Java 文件,构建文件包括 pom.xml、build.gradle 或 build.gradle.kts
核心能力:
使用 Project Loom 的虚拟线程:
在 Executors.newVirtualThreadPerTaskExecutor 上使用 try-with-resources。调用 IntStream.range 从 0 到 10000 并使用 forEach 提交任务,这些任务休眠一秒并返回迭代值。
结构化并发预览模式:
在 new StructuredTaskScope.ShutdownOnFailure 上使用 try-with-resources。通过调用带有 lambda 表达式的 scope.fork 来分派获取用户和订单的任务。调用 然后 。返回一个包含两个任务提供者结果的新复合对象。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
scope.jointhrowIfFailedSwitch 模式匹配:
创建一个接收 Object 参数的 describe 方法。使用 switch 表达式,包含以下 case:带有守卫条件 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 组件解构为变量,返回宽乘以高的绝对值。定义允许 Circle 和 Rectangle 的密封 Shape 接口。实现 Circle 记录,其 area 方法使用 PI 乘以半径的平方。
REST 控制器模式:
创建带有 @RestController 注解、@RequestMapping 为 api/users 和 @RequiredArgsConstructor 的 UserController。注入 UserService。创建带有 @GetMapping 和 @PathVariable 用于 id 的 getUser 方法,返回将 findById 结果映射为 ok 或返回 notFound 的 ResponseEntity。创建带有 @PostMapping、@Valid 注解和 @RequestBody 用于 CreateUserRequest 的 createUser 方法。创建用户,构建 URI 位置,返回带有主体的 created 响应。创建带有 @DeleteMapping 的 deleteUser 方法,根据服务结果返回 noContent 或 notFound。
服务层模式:
创建带有 @Service、@RequiredArgsConstructor 和 @Transactional(readOnly = true) 注解的 UserService。注入 UserRepository 和 PasswordEncoder。创建返回 Optional 的 findById 方法。创建事务性的 create 方法,检查重复的电子邮件并抛出 DuplicateEmailException,使用构建器模式编码密码构建 User,并保存到仓库。
安全配置模式:
创建带有 @Configuration 和 @EnableWebSecurity 注解的 SecurityConfig。定义接收 HttpSecurity 的 filterChain Bean。配置 authorizeHttpRequests,对公共 API 路径使用 permitAll,对管理员路径使用 hasRole('ADMIN'),对其他所有请求使用 authenticated。配置 oauth2ResourceServer 使用 jwt 默认值。将 sessionManagement 设置为 STATELESS 并禁用 csrf。定义返回 BCryptPasswordEncoder 的 passwordEncoder Bean。
实体定义模式:
创建带有 @Entity 和 @Table 注解的 User 实体。添加 Lombok 的 @Getter、@Setter、@NoArgsConstructor 和 @Builder 注解。使用 @Id 和 @GeneratedValue(strategy = 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。添加带有 JPQL 和 LEFT JOIN FETCH 的 @Query 注解用于 findByIdWithOrders,使用 @Param 注解。添加带有 Pageable 用于分页的 findByNameContainingIgnoreCase。
使用记录作为 DTO 的模式:
创建包含 id、name、email 和 status 的 UserDto 记录。添加静态 from 工厂方法,从 User 实体构造记录。创建带有 @NotBlank 和 @Size 注解用于 name、@NotBlank 和 @Email 用于 email、@NotBlank 和 @Size(min = 8) 用于 password 的 CreateUserRequest 记录。
创建带有 @Service 和 @RequiredArgsConstructor 注解的 AsyncUserService。创建 fetchUserDetails 方法,在 try-with-resources 中使用 StructuredTaskScope.ShutdownOnFailure。分派用户和订单查询任务,join 并在失败时抛出异常,返回复合结果。创建 processUsersInParallel 方法,使用 newVirtualThreadPerTaskExecutor 并流式处理用户 ID 来提交处理任务。
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 插件。将工具链 languageVersion 设置为 21。添加 web 和 data-jpa starter 的 implementation 依赖项,以及 test starter 的 testImplementation 依赖项。
单元测试模式:
创建带有 @ExtendWith(MockitoExtension.class) 的测试类。为 UserRepository 添加 @Mock 注解。为 UserService 添加 @InjectMocks 注解。创建 shouldCreateUser 测试,将 existsByEmail 存根为返回 false,save 存根为返回带 id 的用户。调用服务 create 并断言结果 id 等于 1。
使用 TestContainers 的集成测试模式:
创建带有 @Testcontainers 和 @SpringBootTest 注解的测试类。为 PostgreSQL 定义静态 @Container,使用 postgres:16-alpine 镜像。添加 @DynamicPropertySource 以从容器的 getJdbcUrl 设置 datasource.url。自动装配仓库。创建保存用户并断言 id 不为空的测试。
最新文档的库映射:
常见问题:
java -version 并检查 JAVA_HOME 是否指向 Java 21mvn clean compile -X 或 gradle build --info--enable-preview@Transactional 注解或 JOIN FETCH 查询性能提示:
spring.threads.virtual.enabled 设置为 true 来启用虚拟线程全面的参考资料:
最后更新:2026-01-11 状态:生产就绪 (v1.1.0)
每周安装数
78
仓库
GitHub 星标数
882
首次出现
2026年1月21日
安全审计
安装于
opencode65
gemini-cli64
codex62
claude-code61
cursor59
antigravity56
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:
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.
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.
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.
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.
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.
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.
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.
Library mappings for latest documentation:
Common Issues:
Performance Tips:
For comprehensive reference materials:
Last Updated: 2026-01-11 Status: Production Ready (v1.1.0)
Weekly Installs
78
Repository
GitHub Stars
882
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode65
gemini-cli64
codex62
claude-code61
cursor59
antigravity56
2025 Node.js 最佳实践指南:框架选择、架构原则与错误处理
5,100 周安装
AI列表构建器:为创意写作生成高质量随机列表,提升故事熵值
114 周安装
Solana Anchor 开发规范与最佳实践指南 - 提升代码质量与可维护性
119 周安装
Python测试专家技能:pytest单元测试、TDD测试驱动开发与集成测试最佳实践
117 周安装
Components.build 规范:构建现代化、可组合、无障碍 React UI 组件库的完整指南
115 周安装
Better Auth集成指南:Next.js身份验证处理器配置与Cookie处理方案
117 周安装
Google Drive 集成工具:命令行读写、搜索、文件管理,支持 OAuth 身份验证
116 周安装