java-patterns
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "java-patterns":https://skillpi.com/zh/skills/deepskill-805fff8703d52c5fc78273f83703a2ae38d0ae71a8c9eead73292022ffb3f4d9。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
java-patterns:Java 相关模式与实践,涉及 Spring Boot、CompletableFuture、记录类(records)、密封类型(sealed types)、JPA/Hibernate 与虚拟线程。触发器:Java、Spring、JPA、Hibernate、Maven、Gradle、虚拟线程、密封类。
介绍来源: third_party · softspark · 0.0.1 参考来源
SkillPi 解读
- 能完成的任务
- 翻译待完成,请参阅来源文档。
- 实测状态
- 未测试
文件浏览
Frontmatter
name: java-patterns
description: "Java: Spring Boot, CompletableFuture, records, sealed types, JPA/Hibernate, virtual threads. Triggers: Java, Spring, JPA, Hibernate, Maven, Gradle, virtual thread, sealed class."
effort: medium
user-invocable: false
allowed-tools: ReadJava Patterns Skill
Project Structure
Maven / Gradle Standard Layout
my-app/
├── pom.xml (or build.gradle.kts + settings.gradle.kts)
├── src/
│ ├── main/
│ │ ├── java/com/example/myapp/
│ │ │ ├── MyApplication.java
│ │ │ ├── config/
│ │ │ ├── controller/
│ │ │ ├── service/
│ │ │ ├── repository/
│ │ │ ├── model/
│ │ │ │ ├── entity/
│ │ │ │ └── dto/
│ │ │ └── exception/
│ │ └── resources/
│ │ ├── application.yml
│ │ └── db/migration/
│ └── test/
│ ├── java/com/example/myapp/
│ └── resources/application-test.yml
└── target/ (or build/)
Multi-Module
parent/
├── pom.xml (packaging=pom)
├── common/ (shared utilities)
├── domain/ (entities, business rules)
├── api/ (REST controllers, DTOs)
└── app/ (Spring Boot main, wiring)
Idioms / Code Style
Records (Java 16+)
public record UserDto(Long id, String name, String email) {
public UserDto { // compact constructor for validation
Objects.requireNonNull(name, "name must not be null");
Objects.requireNonNull(email, "email must not be null");
}
}
Sealed Classes (Java 17+)
public sealed interface Shape permits Circle, Rectangle, Triangle {
double area();
}
public record Circle(double radius) implements Shape {
public double area() { return Math.PI * radius * radius; }
}
public record Rectangle(double w, double h) implements Shape {
public double area() { return w * h; }
}
public record Triangle(double base, double height) implements Shape {
public double area() { return 0.5 * base * height; }
}
Switch Expressions (Java 14+)
String describe(Shape shape) {
return switch (shape) {
case Circle c -> "Circle r=" + c.radius();
case Rectangle r -> "Rect %sx%s".formatted(r.w(), r.h());
case Triangle t -> "Triangle base=" + t.base();
};
}
// Guard patterns (Java 21+)
String classify(Shape shape) {
return switch (shape) {
case Circle c when c.radius() > 100 -> "large circle";
case Circle c -> "small circle";
case Rectangle r -> "rectangle";
case Triangle t -> "triangle";
};
}
var, Streams, Optional
// var -- use when RHS makes type obvious
var users = new ArrayList<User>();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Avoid: var result = service.process(data); -- type unclear
// Streams
List<String> names = users.stream()
.filter(User::isActive)
.map(User::name)
.sorted()
.toList(); // Java 16+, unmodifiable
Map<Department, List<User>> byDept = users.stream()
.collect(Collectors.groupingBy(User::department));
// Optional -- return type only, never as field or parameter
String city = findByEmail(email)
.map(User::address)
.map(Address::city)
.orElse("Unknown");
// Never call .get() without guard -- use orElse/orElseThrow
// Text blocks (Java 15+)
String json = """
{"name": "%s", "email": "%s"}
""".formatted(name, email);
Error Handling
| Type | When | Examples |
|---|---|---|
| Checked | Recoverable I/O the caller must handle | IOException, SQLException |
| Unchecked | Programming errors, business rule violations | IllegalArgumentException, custom domain exceptions |
Custom Exception Hierarchy
public abstract class DomainException extends RuntimeException {
private final String errorCode;
protected DomainException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public String errorCode() { return errorCode; }
}
public class EntityNotFoundException extends DomainException {
public EntityNotFoundException(String entity, Object id) {
super("NOT_FOUND", "%s with id %s not found".formatted(entity, id));
}
}
Try-With-Resources
try (var conn = dataSource.getConnection();
var stmt = conn.prepareStatement(sql);
var rs = stmt.executeQuery()) {
while (rs.next()) { results.add(mapRow(rs)); }
}
Global Handler (Spring)
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(EntityNotFoundException ex) {
return ResponseEntity.status(404).body(new ErrorResponse(ex.errorCode(), ex.getMessage()));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
var errors = ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage()).toList();
return ResponseEntity.badRequest().body(new ErrorResponse("VALIDATION_ERROR", errors.toString()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneric(Exception ex) {
log.error("Unhandled exception", ex);
return ResponseEntity.internalServerError()
.body(new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred"));
}
}
public record ErrorResponse(String code, String message) {}
Testing Patterns
JUnit 5 + Mockito + AssertJ
@DisplayName("UserService")
class UserServiceTest {
private UserRepository repository;
private UserService service;
@BeforeEach
void setUp() {
repository = mock(UserRepository.class);
service = new UserService(repository);
}
@Test
void createsUserWithValidData() {
var request = new CreateUserRequest("Alice", "alice@example.com");
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
var user = service.createUser(request);
assertThat(user.name()).isEqualTo("Alice");
verify(repository).save(any(User.class));
}
@Test
void throwsWhenEmailExists() {
when(repository.existsByEmail("taken@test.com")).thenReturn(true);
assertThatThrownBy(() -> service.createUser(new CreateUserRequest("Bob", "taken@test.com")))
.isInstanceOf(BusinessRuleViolationException.class)
.hasMessageContaining("email already exists");
}
}
Parameterized Tests
@ParameterizedTest
@CsvSource({"1,1,2", "0,0,0", "-1,1,0", "100,200,300"})
void addReturnsSumOfArguments(int a, int b, int expected) {
assertThat(calculator.add(a, b)).isEqualTo(expected);
}
@ParameterizedTest
@MethodSource("invalidEmails")
void rejectsInvalidEmail(String email) {
assertThatThrownBy(() -> new Email(email)).isInstanceOf(IllegalArgumentException.class);
}
static Stream<String> invalidEmails() {
return Stream.of("", "no-at-sign", "@no-local", "spaces in@email.com");
}
Mockito Extras
// Argument captor
var captor = ArgumentCaptor.forClass(User.class);
verify(repository).save(captor.capture());
assertThat(captor.getValue().name()).isEqualTo("Alice");
// BDD style
given(repository.findById(1L)).willReturn(Optional.of(user));
then(repository).should().findById(1L);
Testcontainers (Integration)
@Testcontainers
@SpringBootTest
class UserRepositoryIT {
@Container
static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16-alpine");
@DynamicPropertySource
static void props(DynamicPropertyRegistry r) {
r.add("spring.datasource.url", pg::getJdbcUrl);
r.add("spring.datasource.username", pg::getUsername);
r.add("spring.datasource.password", pg::getPassword);
}
@Autowired UserRepository repository;
@Test
void savesAndRetrievesUser() {
var saved = repository.save(new User("Alice", "alice@test.com"));
assertThat(repository.findById(saved.getId())).isPresent()
.get().extracting("name").isEqualTo("Alice");
}
}
Common Frameworks
Spring Boot (Controller / Service / Repository)
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping
public List<UserDto> list(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return userService.list(PageRequest.of(page, size));
}
@PostMapping @ResponseStatus(HttpStatus.CREATED)
public UserDto create(@Valid @RequestBody CreateUserRequest request) {
return userService.create(request);
}
}
@Service @Transactional(readOnly = true) @RequiredArgsConstructor
public class UserService {
private final UserRepository repository;
private final UserMapper mapper;
@Transactional
public UserDto create(CreateUserRequest request) {
if (repository.existsByEmail(request.email()))
throw new BusinessRuleViolationException("email already exists");
return mapper.toDto(repository.save(mapper.toEntity(request)));
}
}
public interface UserRepository extends JpaRepository<User, Long> {
boolean existsByEmail(String email);
@Query("SELECT u FROM User u WHERE u.active = true AND u.role = :role")
List<User> findActiveByRole(@Param("role") Role role);
}
Quarkus
Uses Jakarta REST (@Path, @GET, @POST) + CDI (@Inject, @ApplicationScoped). Panache simplifies JPA: implements PanacheRepository<User> gives find(), persist(), list() out of the box. Use @Transactional on mutating endpoints.
Jackson, Lombok, MapStruct
// Jackson -- snake_case response
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public record ApiResponse<T>(T data, @JsonInclude(Include.NON_NULL) String error) {}
// Lombok -- JPA entities only (use records for DTOs)
@Entity @Getter @Setter @NoArgsConstructor(access = PROTECTED)
@Builder @ToString(exclude = "password") @EqualsAndHashCode(of = "id")
public class User {
@Id @GeneratedValue(strategy = IDENTITY) private Long id;
private String name;
private String email;
private String password;
}
// MapStruct
@Mapper(componentModel = "spring")
public interface UserMapper {
UserDto toDto(User entity);
User toEntity(CreateUserRequest request);
}
Performance Tips
JVM Tuning
# Container-friendly (Java 17+)
java -XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0 -jar app.jar
# GC: -XX:+UseZGC (low latency) | -XX:+UseG1GC (balanced, default) | -XX:+UseParallelGC (throughput)
Virtual Threads (Java 21+)
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
var futures = urls.stream().map(url -> executor.submit(() -> fetch(url))).toList();
var results = futures.stream().map(f -> { try { return f.get(); }
catch (Exception e) { throw new RuntimeException(e); } }).toList();
}
// Spring Boot 3.2+: spring.threads.virtual.enabled=true
Profiling with JFR
java -XX:StartFlightRecording=duration=60s,filename=profile.jfr -jar app.jar
jfr print --events jdk.CPULoad,jdk.GCHeapSummary profile.jfr
Common Pitfalls
| Pitfall | Fix |
|---|---|
| String concat in loop | StringBuilder or String.join() |
| Unbounded caches | Caffeine with maximumSize + expireAfterWrite |
| Autoboxing in hot path | Primitive streams (mapToInt) or primitive collections |
| Synchronized everything | ConcurrentHashMap, StampedLock, virtual threads |
| Reflection in tight loop | Cache MethodHandle or use code generation |
Build / Package Management
Maven (key elements)
<properties>
<java.version>21</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version>
</parent>
<!-- Use dependencyManagement + BOM for non-Boot projects -->
Gradle Kotlin DSL
plugins { java; id("org.springframework.boot") version "3.3.0" }
java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.test { useJUnitPlatform() }
Dependency Management
| Concern | Approach |
|---|---|
| Version alignment | BOM import via dependencyManagement / platform() |
| Vulnerability scan | OWASP plugin (dependencyCheckAnalyze) |
| Unused deps | mvn dependency:analyze or Gradle dependency-analysis plugin |
| Reproducible builds | Pin plugin versions, maven-enforcer-plugin |
Anti-Patterns
| Anti-Pattern | Problem | Solution |
|---|---|---|
| God service class | 1000+ lines | Split by domain concern |
| Anemic domain model | Logic only in services | Put behavior on domain objects |
Catching Exception |
Hides bugs | Catch specific types |
@Autowired on fields |
Hidden deps, untestable | Constructor injection |
| Mutable DTOs | Thread-safety issues | Use records |
| Raw JDBC everywhere | Injection risk, boilerplate | JPA/jOOQ with parameterized queries |
Missing @Transactional |
Inconsistent data | Annotate service methods |
| N+1 queries | Performance death | JOIN FETCH or @EntityGraph |
版本历史
-
v6.2.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0
-
v6.1.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0
-
v6.0.0
GitHub ↗
原版更新说明
## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0
-
v5.5.0
GitHub ↗
原版更新说明
### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0
-
v5.4.2
GitHub ↗
原版更新说明
## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2
此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗
当前收录版本
0.0.1
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 提供 Java 现代特性(records、sealed types、虚拟线程)与主流框架(Spring Boot、JPA/Hibernate)的实用代码模式
- 覆盖项目结构、错误处理、测试、性能优化等全链路开发场景,对开发者具有明确指导价值
亮点
- 触发词精准覆盖 Java 生态核心关键词,边界清晰,能有效匹配开发者查询意图
待提升项
-
description 内容重复 原报告严重程度:轻微
顶层 frontmatter 与 skill_body 内部均包含 description 字段,内容重复
改进建议:建议移除 skill_body 内部的 description 字段,保留顶层 frontmatter 中的定义
亮点
- 文档结构清晰,分模块组织,每部分含完整代码示例与说明,frontmatter 完整
亮点
- 内容为静态知识展示,无动态执行风险,可靠性高
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
-
保存或修改文件
先确认输出目录和同名文件是否会被覆盖;重要文件保留备份,优先写入新的输出目录。
主文档提及 · 第 210, 215, 250, 277, 317 行
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。