---
name: modern-java-guidance
description: >-
  Guides coding agents to write modern Java (17/21/25+) and Spring Boot (3.x+) code using version detection and the `mjg` CLI/Hook scanner instead of legacy Java 8 and Spring Boot 2.x patterns. Activate when writing, refactoring, or reviewing Java or Spring Boot projects.
title: modern-java-guidance
canonical_url: https://skilld.dev/gh/wkd09/modern-java-guidance
last_updated: 2026-11-21T01:01:37.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/java-21-25-core.md](https://skilld.dev/api/skills-raw/wkd09/modern-java-guidance/modern-java-guidance/references/java-21-25-core.md), [references/spring-boot-3x.md](https://skilld.dev/api/skills-raw/wkd09/modern-java-guidance/modern-java-guidance/references/spring-boot-3x.md).
>
> If the user asked to install this Skill, run `npx skilld install wkd09/modern-java-guidance/modern-java-guidance`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/modern-java-guidance`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/wkd09/modern-java-guidance/modern-java-guidance) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/modern-java-guidance`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/modern-java-guidance --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/modern-java-guidance --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Modern Java & Spring Boot Guidance (CLI + Hook + Skill)

LLMs heavily default to **Java 8** and **Spring Boot 2.x** idioms (`javax.*`, `WebSecurityConfigurerAdapter`, `RestTemplate`, `@Autowired` field injection, `new Date()`, `list.get(list.size() - 1)`, `Executors.newFixedThreadPool`). Use this skill and the bundled `mjg` CLI to detect the project's actual versions and enforce modern equivalents without breaking legacy codebases.

---

## Step 1: Detect Project Versions First

Before writing or refactoring Java code, run `mjg detect` (or inspect `pom.xml` / `build.gradle.kts` / `build.gradle` / `.java-version`):

```bash
mjg detect .
```

- **Java <= 11**: Respect the project's configured Java version. Do **not** emit Java 17/21 syntax (`record`, `sealed`, `SequencedCollection`, Virtual Threads) or upgrade the build file unless explicitly requested.
- **Java 17**: Use `record`, `sealed` classes/interfaces, `switch` expressions, text blocks, `List.of`/`Map.of`, `var`, and `java.time`. Do not use Java 21 APIs (`SequencedCollection`, Virtual Threads, Record Patterns).
- **Java 21+ (or greenfield code)**: Use Java 21+ idioms including Pattern Matching for `switch`, Record Patterns, `SequencedCollection` (`getFirst()`, `getLast()`, `reversed()`), and Virtual Threads (`Executors.newVirtualThreadPerTaskExecutor()`).
- **Spring Boot 2.x**: Keep `javax.*` and existing Spring Security 5 / `RestTemplate` APIs unless migrating to Boot 3.
- **Spring Boot 3.0–3.1**: Use `jakarta.*`, `SecurityFilterChain` + Lambda DSL + `requestMatchers()`, and constructor injection. (`RestClient` is not available yet; keep `WebClient` or `RestTemplate`.)
- **Spring Boot 3.2–3.3**: Also prefer `RestClient` / `@HttpExchange` over `RestTemplate`, and extracted/layered JARs (`-Djarmode=tools`) for containers.
- **Spring Boot 3.4+**: Also replace deprecated `@MockBean` / `@SpyBean` with `@MockitoBean` / `@MockitoSpyBean`.

---

## Step 2: Legacy vs. Modern Decision Matrix

| Category | ❌ Legacy (Java 8 / Boot 2.x) | ✅ Modern Java 21+ / Spring Boot 3.x+ |
| :--- | :--- | :--- |
| **DTO / Value Objects** | Verbose POJO or `@Data` on immutable DTOs | `public record UserDto(Long id, String email) {}` |
| **Type Dispatch** | `if (x instanceof A) { A a = (A) x; ... }` | Pattern Matching for `switch` + `sealed interface` |
| **First / Last Element** | `list.get(0)`, `list.get(list.size() - 1)` | `list.getFirst()`, `list.getLast()`, `list.reversed()` |
| **I/O Concurrency** | `Executors.newFixedThreadPool(...)` for blocking I/O | `Executors.newVirtualThreadPerTaskExecutor()` |
| **Date & Time** | `new Date()`, `SimpleDateFormat` | `Instant.now()`, `LocalDate`, `DateTimeFormatter` (`java.time`) |
| **Collections** | `Collections.unmodifiableList(Arrays.asList(...))` | `List.of(...)`, `Set.of(...)`, `Map.of(...)` |
| **EE Packages (Boot 3+)** | `import javax.persistence.*`, `javax.validation.*` | `import jakarta.persistence.*`, `jakarta.validation.*` |
| **Spring Security 6** | `extends WebSecurityConfigurerAdapter`, `.antMatchers()`, `.csrf().disable()` | `@Bean SecurityFilterChain`, `.authorizeHttpRequests(a -> a.requestMatchers(...))`, `.csrf(AbstractHttpConfigurer::disable)` |
| **HTTP Client (Boot 3.2+)** | `new RestTemplate()` | `RestClient.builder()` or `@HttpExchange` |
| **Dependency Injection** | `@Autowired` field injection | Constructor injection with `private final` fields |

---

## Step 3: On-Demand Guides & References

For token-efficient lookups without loading full reference files, query the built-in catalog:
```bash
mjg search "<topic>"      # e.g. mjg search "security" or mjg search "virtual-threads"
mjg retrieve <GUIDE_ID>   # e.g. mjg retrieve BOOT-002
```

- **Java 17/21/25 Language & Stdlib Patterns**: Read [references/java-21-25-core.md](https://skilld.dev/api/skills-raw/wkd09/modern-java-guidance/modern-java-guidance/references/java-21-25-core.md)
- **Spring Boot 3.x+ & Spring Security 6 Patterns**: Read [references/spring-boot-3x.md](https://skilld.dev/api/skills-raw/wkd09/modern-java-guidance/modern-java-guidance/references/spring-boot-3x.md)

---

## Step 4: Verify With `mjg check` Before Finishing

After writing or editing `.java` files, run the version-aware scanner (or let the `PostToolUse` hook run it automatically):

```bash
mjg check src/
```

Fix all `error` findings (e.g. `javax.*`, `WebSecurityConfigurerAdapter`) and address `warning` findings unless an external ABI or concurrency constraint (e.g., CPU-bound bounded pool) requires keeping the existing pattern (suppress intentional exceptions inline with `// mjg:ignore <RULE-ID>`). To enforce the same version-gated rules in CI without `mjg`, export a Semgrep Java AST ruleset via `mjg export --format semgrep --path . -o .semgrep/modern-java.yaml`.
