spring-pro
Spring Boot guidance — DI, data access, security, testing, and production-ready Java services.
- License 许可
- MIT
- 最近更新
- 2026-11-07
- Stars
- ★ 0
- Forks
- 1
01 前言 Front Matter
- name
- spring-pro
- category
- development
- description
- Spring Boot guidance — DI, data access, security, testing, and production-ready Java services.
03 SKILL.md 正文
Overview
Spring Boot is the dominant Java framework for backend services: dependency injection, auto-configuration, and a vast ecosystem (Data, Security, Cloud, Batch) let teams build enterprise-grade services with relatively little boilerplate. Its opinions are strong but escape hatches exist everywhere. This skill covers building Spring Boot services correctly — bean design, data access with Spring Data, security configuration, and the operational details (profiles, actuators, graceful shutdown) that production demands.
When to use
- Building a Java/Kotlin backend service or microservice.
- Structuring Spring Boot apps (layers, beans, configuration).
- Securing APIs with Spring Security (JWT, OAuth2).
- Tuning data access (JPA/Hibernate pitfalls, transactions).
- Preparing Spring Boot for production (profiles, observability, containers).
- Migrating Spring Boot across major versions.
- Choosing between Spring MVC and WebFlux.
Core concepts
- IoC and dependency injection. The container wires
@Component/@Service/@Repositorybeans; prefer constructor injection (final fields, testable, no reflection magic). Understand bean scopes — singleton is the default; request/session scopes exist for web contexts. - Auto-configuration. Starters (
spring-boot-starter-web,-data-jpa) configure sensible defaults. Override viaapplication.ymland@ConditionalOn*beans; use@ConfigurationPropertieswith validation for typed config instead of scattered@Value. - Spring Data JPA. Repositories give CRUD + derived queries (
findByEmail) for free. Know the Hibernate underneath: lazy loading, the N+1 problem (@EntityGraph/ fetch joins fix it), and whyOpenSessionInViewis usually better disabled. - Transactions.
@Transactionalboundaries belong at the service layer. Remember: self-invocation bypasses proxies (no transaction applied), checked exceptions don't trigger rollback by default, and long transactions hold connections. - Spring Security. Filter-chain based; modern config uses
SecurityFilterChainbeans, notWebSecurityConfigurerAdapter(removed). For APIs: stateless JWT or OAuth2 resource server; never roll your own password hashing (use the provided encoders). - Profiles and config.
application-{profile}.ymlper environment; secrets from env vars or a secret store, never in the repo. Fail fast on missing required properties. - Actuator. Production-ready endpoints (
/actuator/health,/metrics,/info) — expose selectively, secure them, and wire health checks to your orchestrator. - MVC vs WebFlux. MVC (Servlet, blocking) is the default and right for most apps; WebFlux (reactive, non-blocking) suits high-concurrency I/O with reactive data stores. Don't adopt WebFlux for "performance" without a reactive stack end-to-end — mixed blocking/reactive is the worst of both.
- Validation. Bean Validation (
@NotNull,@Size) on DTOs with@Validat the controller boundary; custom validators for domain rules; consistent error responses via@ControllerAdvice. - Scheduling and async.
@Scheduledfor cron-like tasks (with a distributed lock like ShedLock in multi-instance deploys);@Asyncfor fire-and-forget — with a properly sized thread pool, not the default unbounded one.
Practical workflow
-
Bootstrap. Use Spring Initializr (or the CLI) with the starters you need; prefer Gradle or Maven wrapper committed to the repo; target an LTS Java version.
-
Layer the app.
controller(HTTP only) →service(@Transactionalbusiness logic) →repository(data access); DTOs at the boundary, entities never leaked to clients.@Service @RequiredArgsConstructor public class OrderService { private final OrderRepository orders; @Transactional public OrderDto placeOrder(PlaceOrderCommand cmd) { ... } } -
Configure data access. Connection pool (HikariCP is default — size it: pool ≈ (2 × cores) + spindles for typical workloads), Flyway/Liquibase for migrations (never
ddl-auto: updatein prod), indexes for query patterns. -
Secure the API.
SecurityFilterChainwith stateless sessions, JWT validation, method security (@PreAuthorize) for authorization, CORS locked to known origins.@Bean SecurityFilterChain api(HttpSecurity http) throws Exception { return http.csrf(csrf -> csrf.disable()) .sessionManagement(s -> s.sessionCreationPolicy(STATELESS)) .authorizeHttpRequests(a -> a.requestMatchers("/actuator/health").permitAll() .anyRequest().authenticated()) .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) .build(); } -
Test in slices.
@WebMvcTestfor controllers,@DataJpaTestfor repositories, Testcontainers for integration tests against real Postgres/Redis/Kafka — not mocks of infrastructure. -
Handle errors consistently.
@ControllerAdvicemapping domain exceptions to RFC 9457 problem-details responses; log with correlation IDs; never leak stack traces. -
Observe. Micrometer metrics to Prometheus/Datadog, structured logging (logstash encoder), distributed tracing via OpenTelemetry; dashboards on golden signals per service.
-
Ship. Build a layered container image (Spring Boot's buildpacks or a multi-stage Dockerfile), enable graceful shutdown (
server.shutdown=graceful), expose actuator health, and set JVM memory flags to respect container limits (-XX:MaxRAMPercentage).@RestControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(OrderNotFoundException.class) ProblemDetail handleNotFound(OrderNotFoundException ex) { ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage()); pd.setTitle("Order not found"); return pd; } }
Common pitfalls
- N+1 queries via lazy loading — especially serialized to JSON; use entity graphs or DTO projections.
@Transactionalself-invocation — calling another@Transactionalmethod onthisskips the proxy; extract to another bean.- Field injection — hides dependencies, breaks immutability, complicates tests; use constructor injection.
ddl-auto: updatein production — can drop or corrupt data; use Flyway/Liquibase migrations.- Exposing all actuator endpoints —
/envand/heapdumpleak secrets; expose only health/info/metrics and secure them. - Ignoring graceful shutdown — in-flight requests get killed on deploy; enable it and give the orchestrator a proper termination grace period.
- Oversized Hikari pools — more connections ≠ more throughput; oversized pools cause DB contention and latency spikes.
- OpenSessionInView left on — lazy loading during view rendering causing surprise queries; disable and fetch explicitly.
@Asyncwith default executor — unbounded thread creation under load; define a boundedTaskExecutor.- Catching exceptions inside
@Transactional— swallowing the exception that should trigger rollback; rethrow or mark rollback-only. - Blocking calls in WebFlux handlers — one blocking call stalls the whole event loop; offload with
publishOn(Schedulers.boundedElastic())or stay on MVC. - Fat
@Configurationclasses — hundreds of bean definitions in one file; split configuration by domain like any other code.
04 同仓库更多 Skills
web-scrape
Turn web pages into LLM-ready markdown via the Firecrawl API (renders JS, anti-bot handling). Use when browser_open/fetch fails on JS-heavy pages, or when you need clean markdown/structured extraction from a site. Requires FIRECRAWL_API_KEY.
design-taste-frontend
tasteskill v2, the anti-slop frontend skill. Art direction for websites, distilled from a study of 247 curated gallery sites (One Page Love, Awwwards Sites of the Day). Deals researched directions (idea, composition, type, palette, photographs, section blueprints) from a library, enforces a strict no-slop house style with a real-browser inspector, and runs a look-and-fix loop on screenshots. Use this whenever you build, design, redesign, restyle, polish or review a landing page, marketing site, portfolio, product page, one-pager, hero or any public-facing web page, in any stack (HTML/CSS, React, Next.js, Vue, Svelte, Astro, Tailwind) — also when the user says a page looks generic, templated, "AI-made", sloppy, or asks to make it look designed, premium, award-level or less like every other site. Not for dashboards or app screens.
test-driven-development
Use when implementing any feature or bugfix, before writing implementation code
systematic-debugging
Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
requesting-code-review
Use when completing tasks, implementing major features, or before merging to verify work meets requirements
brainstorming
You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).