[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ET4AF8BT9XY7S6614XNYJY":3,"skill-same:01M7ET4AF8BT9XY7S6614XNYJY":75},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":35,"commitSha":36,"skillDirectory":37,"forksCount":38,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":6,"ownerDescription":41,"updatedAt":42,"install":43,"resources":56},"01M7ET4AF8BT9XY7S6614XNYJY","spring-boot",null,"Use when building, reviewing, testing, securing or configuring a Spring Boot 4 \u002F Framework 7 backend — controllers, services, Spring Data JPA, application.yml, SecurityFilterChain, slice tests. NOT plain modern-Java language work like records or virtual threads (that is `java`); NOT engine-level SQL schema\u002Findex\u002FEXPLAIN (that is `postgresdb`).","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fspring-boot\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: spring-boot\ndescription: \"Use when building, reviewing, testing, securing or configuring a Spring Boot 4 \u002F Framework 7 backend — controllers, services, Spring Data JPA, application.yml, SecurityFilterChain, slice tests. NOT plain modern-Java language work like records or virtual threads (that is `java`); NOT engine-level SQL schema\u002Findex\u002FEXPLAIN (that is `postgresdb`).\"\ntags: [java, spring, jpa, security, backend]\nrecommends: [java, postgresdb, secure-coding, deployment]\norigin: risco\n---\n\n# Spring Boot backends (Boot 4 \u002F Framework 7)\n\nA Spring Boot app is **a thin web layer delegating to a transactional service layer over\nSpring Data JPA repositories** — wired by constructor injection, configured by typed\n`@ConfigurationProperties`, locked down by a `SecurityFilterChain` bean. Controllers\nvalidate input and delegate; they never own business logic, transactions, or persistence.\nHold that shape and most \"where does this go?\" questions answer themselves.\n\n**Pinned stack** (verify against the project's `pom.xml`\u002F`build.gradle` — do not assume):\nSpring Boot 4.0 (GA 2025-11-20), Spring Framework 7, Java 17 baseline \u002F Java 25 LTS, Jakarta\nEE 11 (`jakarta.*`, never `javax.*`), Jackson 3, Spring Security 7, Spring Data JPA \u002F\nHibernate 7, JUnit 5 + Testcontainers, Maven 3.9 \u002F Gradle.\n\nIf you are typing `WebSecurityConfigurerAdapter`, `@MockBean`, field `@Autowired`,\n`authorizeRequests`, or `javax.persistence` — **stop**. Those are the previous generation.\nThe modern idioms below replace every one of them.\n\n## Boundaries\n\n- Plain Java language work (records, sealed types, virtual threads, streams, pattern\n  matching) with no Spring -> [`..\u002Fjava\u002FSKILL.md`](..\u002Fjava\u002FSKILL.md).\n- Async Python FastAPI -> [`..\u002Ffastapi\u002FSKILL.md`](..\u002Ffastapi\u002FSKILL.md). NestJS\u002FNode ->\n  [`..\u002Fnestjs\u002FSKILL.md`](..\u002Fnestjs\u002FSKILL.md). Django -> [`..\u002Fdjango\u002FSKILL.md`](..\u002Fdjango\u002FSKILL.md).\n- Engine-level SQL: schema\u002Findex design, `EXPLAIN`, partitioning, zero-downtime DDL ->\n  [`..\u002Fpostgresdb\u002FSKILL.md`](..\u002Fpostgresdb\u002FSKILL.md) (this skill drives the JPA layer above it).\n- Language-agnostic injection\u002Fauthz\u002Fsecret theory ->\n  [`..\u002Fsecure-coding\u002FSKILL.md`](..\u002Fsecure-coding\u002FSKILL.md).\n- Dockerfile\u002FCompose\u002FCI\u002FCD mechanics -> [`..\u002Fdeployment\u002FSKILL.md`](..\u002Fdeployment\u002FSKILL.md)\n  (keep only a build note here).\n\n## Project layout\n\nPackage by feature, not by layer — colocation keeps a change to one feature in one folder.\n\n```text\ncom.acme.shop\n├── order\u002F\n│   ├── OrderController.java       \u002F\u002F @RestController — web edge\n│   ├── OrderService.java          \u002F\u002F @Service — @Transactional unit of work\n│   ├── OrderRepository.java       \u002F\u002F extends JpaRepository\u003COrder, Long>\n│   ├── Order.java                 \u002F\u002F @Entity (jakarta.persistence)\n│   └── dto\u002FCreateOrderRequest.java, OrderResponse.java   \u002F\u002F records, never entities\n├── config\u002FAppProperties.java      \u002F\u002F @ConfigurationProperties record\n├── security\u002FSecurityConfig.java   \u002F\u002F SecurityFilterChain bean\n└── ShopApplication.java           \u002F\u002F @SpringBootApplication\n```\n\n## Controllers\n\n`@RestController` + DTO records, `@Valid` on the body (Bean Validation, `jakarta.validation`)\nso business code can assume valid data, `ResponseEntity` for 201\u002F`Location`, a\n`@RestControllerAdvice` for one error envelope. The controller parses, validates, delegates\nand maps — any branch with business meaning belongs in the service, where it is transactional\nand unit-testable without MVC. Boot 4 adds first-class versioning via a `version` attribute\non the mapping — one controller serves many versions, no path duplication.\n\n```java\n@RestController\n@RequestMapping(\"\u002Fapi\u002Fusers\")\nclass UserController {\n    private final UserService users;\n    UserController(UserService users) { this.users = users; }   \u002F\u002F constructor injection\n\n    @PostMapping(version = \"1\")                                  \u002F\u002F Boot 4 API versioning\n    ResponseEntity\u003CUserResponse> create(@Valid @RequestBody CreateUserRequest req) {\n        UserResponse body = users.create(req);\n        URI location = URI.create(\"\u002Fapi\u002Fusers\u002F\" + body.id());\n        return ResponseEntity.created(location).body(body);     \u002F\u002F 201 + Location\n    }\n}\n\nrecord CreateUserRequest(@NotBlank String name, @Email String email) {}\nrecord UserResponse(Long id, String name, String email) {}\n```\n\n```java\n@RestControllerAdvice\nclass ApiExceptionHandler {\n    @ExceptionHandler(MethodArgumentNotValidException.class)\n    ResponseEntity\u003CApiError> onInvalid(MethodArgumentNotValidException e) {\n        var details = e.getBindingResult().getFieldErrors().stream()\n            .map(f -> f.getField() + \": \" + f.getDefaultMessage()).toList();\n        return ResponseEntity.badRequest().body(new ApiError(\"validation_failed\", \"Invalid request\", details));\n    }\n}\nrecord ApiError(String code, String message, List\u003CString> details) {}\n```\n\n**Bad -> Good** — never return the entity; it leaks columns and lazy-loads in the serializer:\n\n```java\n\u002F\u002F Bad: leaks columns; lazy fields blow up in the serializer after the tx closes.\n@GetMapping(\"\u002F{id}\") User get(@PathVariable Long id) { return repo.findById(id).orElseThrow(); }\n\u002F\u002F Good: map to a DTO inside the transactional service.\n@GetMapping(\"\u002F{id}\") UserResponse get(@PathVariable Long id) { return users.get(id); }\n```\n\n## Service + transactions\n\nConstructor-injected, `final` fields, `@Transactional` on the write path, `readOnly = true`\non queries (lets Hibernate skip dirty checking). `@Transactional` belongs on service methods,\nnever on a controller or repository: the transaction must wrap the unit of work, not the HTTP\nrequest or a single query.\n\n```java\n@Service\nclass UserService {\n    private final UserRepository repo;\n    private final PasswordEncoder encoder;\n    UserService(UserRepository repo, PasswordEncoder encoder) { this.repo = repo; this.encoder = encoder; }\n\n    @Transactional\n    UserResponse create(CreateUserRequest req) {\n        var user = repo.save(new User(req.name(), req.email(), encoder.encode(req.rawPassword())));\n        return new UserResponse(user.getId(), user.getName(), user.getEmail());\n    }\n\n    @Transactional(readOnly = true)\n    UserResponse get(Long id) {\n        return repo.findById(id).map(this::toResponse).orElseThrow(() -> new NotFoundException(id));\n    }\n}\n```\n\nTwo traps that produce \"my `@Transactional` isn't rolling back\":\n- **Self-invocation.** Calling `this.other()` inside the same bean bypasses the proxy, so its\n  `@Transactional` is ignored. Split into another bean or accept the outer transaction.\n- **Checked exceptions don't roll back by default.** Spring rolls back on `RuntimeException`\n  only; use `@Transactional(rollbackFor = ...)` for checked ones.\n\n**Bad -> Good** — field injection vs constructor:\n\n```java\n\u002F\u002F Bad: not testable with `new`, hides missing beans until runtime, allows final-less mutation.\n@Autowired private UserRepository repo;\n\u002F\u002F Good:\nprivate final UserRepository repo;\nUserService(UserRepository repo) { this.repo = repo; }\n```\n\n## JPA persistence\n\n`jakarta.persistence` imports (never `javax`). Spring Data gives you derived queries for free\nand `@Query` for the rest; `Pageable`\u002F`Page` for paging.\n\n```java\nimport jakarta.persistence.*;\n\n@Entity @Table(name = \"users\")\nclass User {\n    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;\n    private String name;\n    @Column(unique = true) private String email;\n    @OneToMany(mappedBy = \"user\") private List\u003COrder> orders = new ArrayList\u003C>();\n    \u002F\u002F getters; protected no-arg ctor for Hibernate\n}\n\ninterface UserRepository extends JpaRepository\u003CUser, Long> {\n    Optional\u003CUser> findByEmail(String email);                       \u002F\u002F derived query\n    Page\u003CUser> findByNameContaining(String q, Pageable page);       \u002F\u002F paginated\n\n    @Query(\"select u from User u join fetch u.orders where u.id = :id\")\n    Optional\u003CUser> findWithOrders(@Param(\"id\") Long id);            \u002F\u002F fetch join kills N+1\n}\n```\n\n**N+1 symptom:** iterating a lazy collection issues one query per parent. Fix with a\n`join fetch`, an `@EntityGraph`, or `@BatchSize`. **`LazyInitializationException`** means you\ntouched a lazy field after the transaction (and its Hibernate session) closed — map to a DTO\n*inside* the `@Transactional` service, or fetch eagerly for that path. Relationship\u002Fcascade\ndepth, projections, Specifications, optimistic locking and migration tooling are in\n[`references\u002Fjpa.md`](references\u002Fjpa.md).\n\n## Configuration & profiles\n\n```yaml\n# application.yml — no secrets committed here; import them at boot.\nspring:\n  config:\n    import: \"optional:configtree:\u002Frun\u002Fsecrets\u002F\"   # mount real secrets at runtime\n  datasource:\n    url: ${DB_URL}\n    username: ${DB_USER}\n    password: ${DB_PASSWORD}\napp:\n  invite-ttl: 24h\n  max-orders-per-day: 50\n---\nspring:\n  config:\n    activate:\n      on-profile: dev\napp:\n  max-orders-per-day: 5\n```\n\n```java\n@ConfigurationProperties(prefix = \"app\")\nrecord AppProperties(Duration inviteTtl, int maxOrdersPerDay) {}   \u002F\u002F typed, validated at startup\n\u002F\u002F register once: @EnableConfigurationProperties(AppProperties.class) on a @Configuration\n```\n\n**Bad -> Good** — scattered `@Value(\"${app.max-orders-per-day}\")` strings vs one injected\n`AppProperties` record. One typed binding beats string keys sprinkled across the codebase and\nfails fast on a missing\u002Fmistyped key instead of NPE-ing later.\n\n## Security\n\nA single `SecurityFilterChain` bean with the lambda DSL, stateless for token APIs, JWT via the\nresource server.\n\n```java\n@Configuration\n@EnableMethodSecurity                                            \u002F\u002F enables @PreAuthorize\nclass SecurityConfig {\n    @Bean\n    SecurityFilterChain api(HttpSecurity http) throws Exception {\n        http\n          .csrf(csrf -> csrf.disable())                          \u002F\u002F OK: stateless token API, no cookies\n          .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))\n          .authorizeHttpRequests(auth -> auth\n              .requestMatchers(HttpMethod.POST, \"\u002Fapi\u002Fusers\").permitAll()\n              .requestMatchers(\"\u002Fapi\u002Fadmin\u002F**\").hasRole(\"ADMIN\")\n              .anyRequest().authenticated())\n          .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));\n        return http.build();\n    }\n\n    @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }\n}\n```\n\nOrder `requestMatchers` from most specific to least — the first match wins, so a broad\n`permitAll` placed early opens routes you meant to lock. Full JWT\u002FOAuth2 client, method\nsecurity, CORS, and CSRF posture (token vs cookie apps) live in\n[`references\u002Fsecurity.md`](references\u002Fsecurity.md). For the language-agnostic authz\u002Fsecret\nprinciples behind these rules, see [`..\u002Fsecure-coding\u002FSKILL.md`](..\u002Fsecure-coding\u002FSKILL.md).\n\n## Testing\n\nPick the narrowest slice that exercises what you changed — `@SpringBootTest` only when you\ngenuinely need the full context:\n\n| Slice | Loads | Use for | Collaborators |\n|---|---|---|---|\n| `@WebMvcTest` | web layer + Security + MockMvc | one controller's HTTP contract | `@MockitoBean` the service |\n| `@DataJpaTest` | JPA + in-memory\u002FTC DB, rolls back per test | repository queries, mappings | real repo, test DB |\n| `@SpringBootTest` | full context | end-to-end \u002F integration | real beans, Testcontainers |\n\n`@MockBean`\u002F`@SpyBean` are removed — use `@MockitoBean`\u002F`@MockitoSpyBean` from\n`org.springframework.test.context.bean.override.mockito`.\n\n```java\n@WebMvcTest(UserController.class)\nclass UserControllerTest {\n    @Autowired MockMvc mvc;\n    @MockitoBean UserService users;                              \u002F\u002F not @MockBean\n\n    @Test void rejectsBlankName() throws Exception {\n        mvc.perform(post(\"\u002Fapi\u002Fusers\").contentType(MediaType.APPLICATION_JSON)\n                .content(\"{\\\"name\\\":\\\"\\\",\\\"email\\\":\\\"a@b.co\\\"}\"))\n           .andExpect(status().isBadRequest());\n    }\n}\n```\n\nIntegration DB via Testcontainers + `@ServiceConnection` (auto-wires connection details, no\n`@DynamicPropertySource`):\n\n```java\n@TestConfiguration(proxyBeanMethods = false)\nclass ContainersConfig {\n    @Bean @ServiceConnection\n    PostgreSQLContainer\u003C?> postgres() { return new PostgreSQLContainer\u003C>(\"postgres:17\"); }\n}\n```\n\nSlice deep dive, container reuse, `MockMvcTester`\u002F`WebTestClient`, and the CI gate are in\n[`references\u002Ftesting.md`](references\u002Ftesting.md).\n\n## HTTP clients & resilience\n\nOutbound calls: declare an `@HttpExchange` interface and register it — no manual\n`RestTemplate`\u002F`HttpServiceProxyFactory` boilerplate.\n\n```java\n@HttpExchange(\"\u002Fv1\")\ninterface BillingClient {\n    @GetExchange(\"\u002Finvoices\u002F{id}\") Invoice invoice(@PathVariable String id);\n}\n\u002F\u002F register: @ImportHttpServices(group = \"billing\", types = BillingClient.class) on a @Configuration\n```\n\n`RestClient` is the modern synchronous client for ad-hoc calls. For built-in resilience,\n`@Retryable` and `@ConcurrencyLimit` are core in Framework 7 — no extra Spring Retry\ndependency for the basics.\n\n## Anti-patterns\n\n| Anti-pattern | Why it's wrong | Do instead |\n|---|---|---|\n| Extend `WebSecurityConfigurerAdapter` | Removed in Security 6\u002F7 | `SecurityFilterChain` bean + lambda DSL |\n| `@Autowired` on a field | Untestable, hides missing beans till runtime | constructor injection, `final` fields |\n| `@Transactional` on a `@RestController` | Tx must wrap the unit of work, not the request | put it on the service method |\n| Business branching in the controller | Not transactional, needs MVC to test | move the decision into the `@Service` |\n| Return the `@Entity` from a controller | Leaks columns, lazy-loads in serializer (LIE) | map to a DTO record inside the tx |\n| Request body reaching the service unvalidated | Business code can no longer assume valid data | `@Valid` + `jakarta.validation` at the edge |\n| Scattered `@Value(\"${...}\")` config keys | String keys, no validation, fails late | one typed `@ConfigurationProperties` record |\n| Use `@MockBean` \u002F `@SpyBean` | Replaced in Boot 4 | `@MockitoBean` \u002F `@MockitoSpyBean` |\n| `import javax.persistence` \u002F `javax.validation` | Jakarta EE 11 baseline | `jakarta.*` |\n| `authorizeRequests` \u002F `antMatchers` | Gone in Security 6\u002F7 | `authorizeHttpRequests` + `requestMatchers` |\n| `csrf().disable()` with no rationale | Silently opens cookie-session apps | disable only for stateless token APIs; comment why |\n| `@SpringBootTest` for one controller | Slow, loads everything | `@WebMvcTest` + `@MockitoBean` |\n| One 800-line `@Service` | Untestable, tangled transactions | split per use case \u002F aggregate |\n| `catch (Exception e)` and echo `e.getMessage()` | Leaks internals, swallows bugs | `@RestControllerAdvice` + typed error envelope |\n| Serialize a lazy collection after the tx closes | `LazyInitializationException` \u002F N+1 | fetch join or `@EntityGraph`, map in-tx |\n\n`scripts\u002Fverify.sh` greps a project for the legacy idioms above (read-only, best effort).\n\n## Quick reference\n\n| Task | Idiom |\n|---|---|\n| Inject a dependency | constructor arg, `final` field |\n| Expose an endpoint | `@RestController` + `@GetMapping`\u002F`@PostMapping(version=)` |\n| Validate input | `@Valid @RequestBody` + `jakarta.validation` annotations |\n| Get by id | `repo.findById(id).orElseThrow(...)` in a `readOnly` tx |\n| Paginate | `Page\u003CT> findBy...(..., Pageable page)` |\n| Custom query | `@Query(\"select ... join fetch ...\")` |\n| Transaction boundary | `@Transactional` on the service method |\n| Hash a password | `PasswordEncoder` bean (`BCryptPasswordEncoder`) |\n| Lock down routes | `SecurityFilterChain` + `authorizeHttpRequests`\u002F`requestMatchers` |\n| JWT API | `oauth2ResourceServer(o -> o.jwt(...))`, stateless session |\n| Mock a collaborator in a test | `@MockitoBean` |\n| Integration DB | Testcontainers `@Bean` + `@ServiceConnection` |\n\n## Project grounding\n\nIf the repo has a `02-DOCS\u002F` wiki, record stack decisions (Boot version, security posture,\ntest strategy, migration tool) in `02-DOCS\u002Fwiki\u002Fstack\u002Fspring-boot.md` and link it from the\n`CLAUDE.md` Knowledge map. This is recorded, not gated — if there is no `02-DOCS\u002F`, skip\nsilently; you may suggest the project harness if the user wants persistent docs.\n","# Spring Boot backends (Boot 4 \u002F Framework 7)\n\nA Spring Boot app is **a thin web layer delegating to a transactional service layer over\nSpring Data JPA repositories** — wired by constructor injection, configured by typed\n`@ConfigurationProperties`, locked down by a `SecurityFilterChain` bean. Controllers\nvalidate input and delegate; they never own business logic, transactions, or persistence.\nHold that shape and most \"where does this go?\" questions answer themselves.\n\n**Pinned stack** (verify against the project's `pom.xml`\u002F`build.gradle` — do not assume):\nSpring Boot 4.0 (GA 2025-11-20), Spring Framework 7, Java 17 baseline \u002F Java 25 LTS, Jakarta\nEE 11 (`jakarta.*`, never `javax.*`), Jackson 3, Spring Security 7, Spring Data JPA \u002F\nHibernate 7, JUnit 5 + Testcontainers, Maven 3.9 \u002F Gradle.\n\nIf you are typing `WebSecurityConfigurerAdapter`, `@MockBean`, field `@Autowired`,\n`authorizeRequests`, or `javax.persistence` — **stop**. Those are the previous generation.\nThe modern idioms below replace every one of them.\n\n## Boundaries\n\n- Plain Java language work (records, sealed types, virtual threads, streams, pattern\n  matching) with no Spring -> [`..\u002Fjava\u002FSKILL.md`](..\u002Fjava\u002FSKILL.md).\n- Async Python FastAPI -> [`..\u002Ffastapi\u002FSKILL.md`](..\u002Ffastapi\u002FSKILL.md). NestJS\u002FNode ->\n  [`..\u002Fnestjs\u002FSKILL.md`](..\u002Fnestjs\u002FSKILL.md). Django -> [`..\u002Fdjango\u002FSKILL.md`](..\u002Fdjango\u002FSKILL.md).\n- Engine-level SQL: schema\u002Findex design, `EXPLAIN`, partitioning, zero-downtime DDL ->\n  [`..\u002Fpostgresdb\u002FSKILL.md`](..\u002Fpostgresdb\u002FSKILL.md) (this skill drives the JPA layer above it).\n- Language-agnostic injection\u002Fauthz\u002Fsecret theory ->\n  [`..\u002Fsecure-coding\u002FSKILL.md`](..\u002Fsecure-coding\u002FSKILL.md).\n- Dockerfile\u002FCompose\u002FCI\u002FCD mechanics -> [`..\u002Fdeployment\u002FSKILL.md`](..\u002Fdeployment\u002FSKILL.md)\n  (keep only a build note here).\n\n## Project layout\n\nPackage by feature, not by layer — colocation keeps a change to one feature in one folder.\n\n```text\ncom.acme.shop\n├── order\u002F\n│   ├── OrderController.java       \u002F\u002F @RestController — web edge\n│   ├── OrderService.java          \u002F\u002F @Service — @Transactional unit of work\n│   ├── OrderRepository.java       \u002F\u002F extends JpaRepository\u003COrder, Long>\n│   ├── Order.java                 \u002F\u002F @Entity (jakarta.persistence)\n│   └── dto\u002FCreateOrderRequest.java, OrderResponse.java   \u002F\u002F records, never entities\n├── config\u002FAppProperties.java      \u002F\u002F @ConfigurationProperties record\n├── security\u002FSecurityConfig.java   \u002F\u002F SecurityFilterChain bean\n└── ShopApplication.java           \u002F\u002F @SpringBootApplication\n```\n\n## Controllers\n\n`@RestController` + DTO records, `@Valid` on the body (Bean Validation, `jakarta.validation`)\nso business code can assume valid data, `ResponseEntity` for 201\u002F`Location`, a\n`@RestControllerAdvice` for one error envelope. The controller parses, validates, delegates\nand maps — any branch with business meaning belongs in the service, where it is transactional\nand unit-testable without MVC. Boot 4 adds first-class versioning via a `version` attribute\non the mapping — one controller serves many versions, no path duplication.\n\n```java\n@RestController\n@RequestMapping(\"\u002Fapi\u002Fusers\")\nclass UserController {\n    private final UserService users;\n    UserController(UserService users) { this.users = users; }   \u002F\u002F constructor injection\n\n    @PostMapping(version = \"1\")                                  \u002F\u002F Boot 4 API versioning\n    ResponseEntity\u003CUserResponse> create(@Valid @RequestBody CreateUserRequest req) {\n        UserResponse body = users.create(req);\n        URI location = URI.create(\"\u002Fapi\u002Fusers\u002F\" + body.id());\n        return ResponseEntity.created(location).body(body);     \u002F\u002F 201 + Location\n    }\n}\n\nrecord CreateUserRequest(@NotBlank String name, @Email String email) {}\nrecord UserResponse(Long id, String name, String email) {}\n```\n\n```java\n@RestControllerAdvice\nclass ApiExceptionHandler {\n    @ExceptionHandler(MethodArgumentNotValidException.class)\n    ResponseEntity\u003CApiError> onInvalid(MethodArgumentNotValidException e) {\n        var details = e.getBindingResult().getFieldErrors().stream()\n            .map(f -> f.getField() + \": \" + f.getDefaultMessage()).toList();\n        return ResponseEntity.badRequest().body(new ApiError(\"validation_failed\", \"Invalid request\", details));\n    }\n}\nrecord ApiError(String code, String message, List\u003CString> details) {}\n```\n\n**Bad -> Good** — never return the entity; it leaks columns and lazy-loads in the serializer:\n\n```java\n\u002F\u002F Bad: leaks columns; lazy fields blow up in the serializer after the tx closes.\n@GetMapping(\"\u002F{id}\") User get(@PathVariable Long id) { return repo.findById(id).orElseThrow(); }\n\u002F\u002F Good: map to a DTO inside the transactional service.\n@GetMapping(\"\u002F{id}\") UserResponse get(@PathVariable Long id) { return users.get(id); }\n```\n\n## Service + transactions\n\nConstructor-injected, `final` fields, `@Transactional` on the write path, `readOnly = true`\non queries (lets Hibernate skip dirty checking). `@Transactional` belongs on service methods,\nnever on a controller or repository: the transaction must wrap the unit of work, not the HTTP\nrequest or a single query.\n\n```java\n@Service\nclass UserService {\n    private final UserRepository repo;\n    private final PasswordEncoder encoder;\n    UserService(UserRepository repo, PasswordEncoder encoder) { this.repo = repo; this.encoder = encoder; }\n\n    @Transactional\n    UserResponse create(CreateUserRequest req) {\n        var user = repo.save(new User(req.name(), req.email(), encoder.encode(req.rawPassword())));\n        return new UserResponse(user.getId(), user.getName(), user.getEmail());\n    }\n\n    @Transactional(readOnly = true)\n    UserResponse get(Long id) {\n        return repo.findById(id).map(this::toResponse).orElseThrow(() -> new NotFoundException(id));\n    }\n}\n```\n\nTwo traps that produce \"my `@Transactional` isn't rolling back\":\n- **Self-invocation.** Calling `this.other()` inside the same bean bypasses the proxy, so its\n  `@Transactional` is ignored. Split into another bean or accept the outer transaction.\n- **Checked exceptions don't roll back by default.** Spring rolls back on `RuntimeException`\n  only; use `@Transactional(rollbackFor = ...)` for checked ones.\n\n**Bad -> Good** — field injection vs constructor:\n\n```java\n\u002F\u002F Bad: not testable with `new`, hides missing beans until runtime, allows final-less mutation.\n@Autowired private UserRepository repo;\n\u002F\u002F Good:\nprivate final UserRepository repo;\nUserService(UserRepository repo) { this.repo = repo; }\n```\n\n## JPA persistence\n\n`jakarta.persistence` imports (never `javax`). Spring Data gives you derived queries for free\nand `@Query` for the rest; `Pageable`\u002F`Page` for paging.\n\n```java\nimport jakarta.persistence.*;\n\n@Entity @Table(name = \"users\")\nclass User {\n    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;\n    private String name;\n    @Column(unique = true) private String email;\n    @OneToMany(mappedBy = \"user\") private List\u003COrder> orders = new ArrayList\u003C>();\n    \u002F\u002F getters; protected no-arg ctor for Hibernate\n}\n\ninterface UserRepository extends JpaRepository\u003CUser, Long> {\n    Optional\u003CUser> findByEmail(String email);                       \u002F\u002F derived query\n    Page\u003CUser> findByNameContaining(String q, Pageable page);       \u002F\u002F paginated\n\n    @Query(\"select u from User u join fetch u.orders where u.id = :id\")\n    Optional\u003CUser> findWithOrders(@Param(\"id\") Long id);            \u002F\u002F fetch join kills N+1\n}\n```\n\n**N+1 symptom:** iterating a lazy collection issues one query per parent. Fix with a\n`join fetch`, an `@EntityGraph`, or `@BatchSize`. **`LazyInitializationException`** means you\ntouched a lazy field after the transaction (and its Hibernate session) closed — map to a DTO\n*inside* the `@Transactional` service, or fetch eagerly for that path. Relationship\u002Fcascade\ndepth, projections, Specifications, optimistic locking and migration tooling are in\n[`references\u002Fjpa.md`](references\u002Fjpa.md).\n\n## Configuration & profiles\n\n```yaml\n# application.yml — no secrets committed here; import them at boot.\nspring:\n  config:\n    import: \"optional:configtree:\u002Frun\u002Fsecrets\u002F\"   # mount real secrets at runtime\n  datasource:\n    url: ${DB_URL}\n    username: ${DB_USER}\n    password: ${DB_PASSWORD}\napp:\n  invite-ttl: 24h\n  max-orders-per-day: 50\n---\nspring:\n  config:\n    activate:\n      on-profile: dev\napp:\n  max-orders-per-day: 5\n```\n\n```java\n@ConfigurationProperties(prefix = \"app\")\nrecord AppProperties(Duration inviteTtl, int maxOrdersPerDay) {}   \u002F\u002F typed, validated at startup\n\u002F\u002F register once: @EnableConfigurationProperties(AppProperties.class) on a @Configuration\n```\n\n**Bad -> Good** — scattered `@Value(\"${app.max-orders-per-day}\")` strings vs one injected\n`AppProperties` record. One typed binding beats string keys sprinkled across the codebase and\nfails fast on a missing\u002Fmistyped key instead of NPE-ing later.\n\n## Security\n\nA single `SecurityFilterChain` bean with the lambda DSL, stateless for token APIs, JWT via the\nresource server.\n\n```java\n@Configuration\n@EnableMethodSecurity                                            \u002F\u002F enables @PreAuthorize\nclass SecurityConfig {\n    @Bean\n    SecurityFilterChain api(HttpSecurity http) throws Exception {\n        http\n          .csrf(csrf -> csrf.disable())                          \u002F\u002F OK: stateless token API, no cookies\n          .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))\n          .authorizeHttpRequests(auth -> auth\n              .requestMatchers(HttpMethod.POST, \"\u002Fapi\u002Fusers\").permitAll()\n              .requestMatchers(\"\u002Fapi\u002Fadmin\u002F**\").hasRole(\"ADMIN\")\n              .anyRequest().authenticated())\n          .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));\n        return http.build();\n    }\n\n    @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }\n}\n```\n\nOrder `requestMatchers` from most specific to least — the first match wins, so a broad\n`permitAll` placed early opens routes you meant to lock. Full JWT\u002FOAuth2 client, method\nsecurity, CORS, and CSRF posture (token vs cookie apps) live in\n[`references\u002Fsecurity.md`](references\u002Fsecurity.md). For the language-agnostic authz\u002Fsecret\nprinciples behind these rules, see [`..\u002Fsecure-coding\u002FSKILL.md`](..\u002Fsecure-coding\u002FSKILL.md).\n\n## Testing\n\nPick the narrowest slice that exercises what you changed — `@SpringBootTest` only when you\ngenuinely need the full context:\n\n| Slice | Loads | Use for | Collaborators |\n|---|---|---|---|\n| `@WebMvcTest` | web layer + Security + MockMvc | one controller's HTTP contract | `@MockitoBean` the service |\n| `@DataJpaTest` | JPA + in-memory\u002FTC DB, rolls back per test | repository queries, mappings | real repo, test DB |\n| `@SpringBootTest` | full context | end-to-end \u002F integration | real beans, Testcontainers |\n\n`@MockBean`\u002F`@SpyBean` are removed — use `@MockitoBean`\u002F`@MockitoSpyBean` from\n`org.springframework.test.context.bean.override.mockito`.\n\n```java\n@WebMvcTest(UserController.class)\nclass UserControllerTest {\n    @Autowired MockMvc mvc;\n    @MockitoBean UserService users;                              \u002F\u002F not @MockBean\n\n    @Test void rejectsBlankName() throws Exception {\n        mvc.perform(post(\"\u002Fapi\u002Fusers\").contentType(MediaType.APPLICATION_JSON)\n                .content(\"{\\\"name\\\":\\\"\\\",\\\"email\\\":\\\"a@b.co\\\"}\"))\n           .andExpect(status().isBadRequest());\n    }\n}\n```\n\nIntegration DB via Testcontainers + `@ServiceConnection` (auto-wires connection details, no\n`@DynamicPropertySource`):\n\n```java\n@TestConfiguration(proxyBeanMethods = false)\nclass ContainersConfig {\n    @Bean @ServiceConnection\n    PostgreSQLContainer\u003C?> postgres() { return new PostgreSQLContainer\u003C>(\"postgres:17\"); }\n}\n```\n\nSlice deep dive, container reuse, `MockMvcTester`\u002F`WebTestClient`, and the CI gate are in\n[`references\u002Ftesting.md`](references\u002Ftesting.md).\n\n## HTTP clients & resilience\n\nOutbound calls: declare an `@HttpExchange` interface and register it — no manual\n`RestTemplate`\u002F`HttpServiceProxyFactory` boilerplate.\n\n```java\n@HttpExchange(\"\u002Fv1\")\ninterface BillingClient {\n    @GetExchange(\"\u002Finvoices\u002F{id}\") Invoice invoice(@PathVariable String id);\n}\n\u002F\u002F register: @ImportHttpServices(group = \"billing\", types = BillingClient.class) on a @Configuration\n```\n\n`RestClient` is the modern synchronous client for ad-hoc calls. For built-in resilience,\n`@Retryable` and `@ConcurrencyLimit` are core in Framework 7 — no extra Spring Retry\ndependency for the basics.\n\n## Anti-patterns\n\n| Anti-pattern | Why it's wrong | Do instead |\n|---|---|---|\n| Extend `WebSecurityConfigurerAdapter` | Removed in Security 6\u002F7 | `SecurityFilterChain` bean + lambda DSL |\n| `@Autowired` on a field | Untestable, hides missing beans till runtime | constructor injection, `final` fields |\n| `@Transactional` on a `@RestController` | Tx must wrap the unit of work, not the request | put it on the service method |\n| Business branching in the controller | Not transactional, needs MVC to test | move the decision into the `@Service` |\n| Return the `@Entity` from a controller | Leaks columns, lazy-loads in serializer (LIE) | map to a DTO record inside the tx |\n| Request body reaching the service unvalidated | Business code can no longer assume valid data | `@Valid` + `jakarta.validation` at the edge |\n| Scattered `@Value(\"${...}\")` config keys | String keys, no validation, fails late | one typed `@ConfigurationProperties` record |\n| Use `@MockBean` \u002F `@SpyBean` | Replaced in Boot 4 | `@MockitoBean` \u002F `@MockitoSpyBean` |\n| `import javax.persistence` \u002F `javax.validation` | Jakarta EE 11 baseline | `jakarta.*` |\n| `authorizeRequests` \u002F `antMatchers` | Gone in Security 6\u002F7 | `authorizeHttpRequests` + `requestMatchers` |\n| `csrf().disable()` with no rationale | Silently opens cookie-session apps | disable only for stateless token APIs; comment why |\n| `@SpringBootTest` for one controller | Slow, loads everything | `@WebMvcTest` + `@MockitoBean` |\n| One 800-line `@Service` | Untestable, tangled transactions | split per use case \u002F aggregate |\n| `catch (Exception e)` and echo `e.getMessage()` | Leaks internals, swallows bugs | `@RestControllerAdvice` + typed error envelope |\n| Serialize a lazy collection after the tx closes | `LazyInitializationException` \u002F N+1 | fetch join or `@EntityGraph`, map in-tx |\n\n`scripts\u002Fverify.sh` greps a project for the legacy idioms above (read-only, best effort).\n\n## Quick reference\n\n| Task | Idiom |\n|---|---|\n| Inject a dependency | constructor arg, `final` field |\n| Expose an endpoint | `@RestController` + `@GetMapping`\u002F`@PostMapping(version=)` |\n| Validate input | `@Valid @RequestBody` + `jakarta.validation` annotations |\n| Get by id | `repo.findById(id).orElseThrow(...)` in a `readOnly` tx |\n| Paginate | `Page\u003CT> findBy...(..., Pageable page)` |\n| Custom query | `@Query(\"select ... join fetch ...\")` |\n| Transaction boundary | `@Transactional` on the service method |\n| Hash a password | `PasswordEncoder` bean (`BCryptPasswordEncoder`) |\n| Lock down routes | `SecurityFilterChain` + `authorizeHttpRequests`\u002F`requestMatchers` |\n| JWT API | `oauth2ResourceServer(o -> o.jwt(...))`, stateless session |\n| Mock a collaborator in a test | `@MockitoBean` |\n| Integration DB | Testcontainers `@Bean` + `@ServiceConnection` |\n\n## Project grounding\n\nIf the repo has a `02-DOCS\u002F` wiki, record stack decisions (Boot version, security posture,\ntest strategy, migration tool) in `02-DOCS\u002Fwiki\u002Fstack\u002Fspring-boot.md` and link it from the\n`CLAUDE.md` Knowledge map. This is recorded, not gated — if there is no `02-DOCS\u002F`, skip\nsilently; you may suggest the project harness if the user wants persistent docs.\n",{"name":5,"tags":24,"origin":30,"recommends":31,"description":7},[25,26,27,28,29],"java","spring","jpa","security","backend","risco",[25,32,33,34],"postgresdb","secure-coding","deployment","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","04-安全渗透\u002Fspring-boot",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill spring-boot",{"tool":49,"command":50},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill spring-boot",{"tool":52,"command":53},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill spring-boot","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fspring-boot\u002FSKILL.md",true,[57,63,67,71],{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"evals\u002Fcases.yaml","REFERENCE","参考文档",3010,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fspring-boot\u002Fevals\u002Fcases.yaml",{"path":64,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":65,"sourceHtmlUrl":66},"evals\u002FREADME.md",854,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fspring-boot\u002Fevals\u002FREADME.md",{"path":68,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Fjpa.md",3685,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fspring-boot\u002Freferences\u002Fjpa.md",{"path":72,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Ftesting.md",3933,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fspring-boot\u002Freferences\u002Ftesting.md",[76,84,89,96,103,110],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":83},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":85,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":83},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":83},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":83},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":83},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":83},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]