java-patterns
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "java-patterns" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-805fff8703d52c5fc78273f83703a2ae38d0ae71a8c9eead73292022ffb3f4d9. Verify the upstream source and version against https://github.com/softspark/ai-toolkit before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
java-patterns: Java patterns and practices covering Spring Boot, CompletableFuture, record types, sealed types, JPA/Hibernate, and virtual threads. Triggers: Java, Spring, JPA, Hibernate, Maven, Gradle, virtual thread, sealed class.
Introduction source: third_party · softspark · 0.0.1 Reference
SkillPi interpretation
- Tasks
- Java: Spring Boot, CompletableFuture, records, sealed types, JPA/Hibernate, virtual threads. Triggers: Java, Spring, JPA, Hibernate, Maven, Gradle, virtual thread, sealed class.
- Testing
- Not tested
Browse files
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 |
Version history
-
v6.2.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0
-
v6.1.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0
-
v6.0.0
GitHub ↗
Original release notes
## 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 ↗
Original release notes
### 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 ↗
Original release notes
## 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
Only the five most recent versions are shown. View full version history at the source ↗
Current listing version
0.0.1
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供 Java 现代特性(records、sealed types、虚拟线程)与主流框架(Spring Boot、JPA/Hibernate)的实用代码模式
- 覆盖项目结构、错误处理、测试、性能优化等全链路开发场景,对开发者具有明确指导价值
Highlights
- 触发词精准覆盖 Java 生态核心关键词,边界清晰,能有效匹配开发者查询意图
Areas to improve
-
description 内容重复 Reported severity: Minor
顶层 frontmatter 与 skill_body 内部均包含 description 字段,内容重复
Recommendation: 建议移除 skill_body 内部的 description 字段,保留顶层 frontmatter 中的定义
Highlights
- 文档结构清晰,分模块组织,每部分含完整代码示例与说明,frontmatter 完整
Highlights
- 内容为静态知识展示,无动态执行风险,可靠性高
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Save or modify files
Confirm the output directory and whether existing files will be replaced. Back up important files and prefer a new output directory.
Mentioned in main document · lines 210, 215, 250, 277, 317
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.