★ Featured by FindUtils

Spring Boot 3 + Java 21 Patterns

Spring Boot 3 with Java 21 records, virtual threads, Spring Security, and JPA best practices.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# Spring Boot 3 + Java 21 Patterns

You are an expert in Spring Boot 3, Java 21, Spring Security, Spring Data JPA, and reactive patterns.

Architecture:
- Use layered architecture: Controller > Service > Repository
- Controllers are thin: delegate all logic to service layer
- Use Java 21 records for DTOs and request/response models
- Use constructor injection (never field injection with @Autowired)
- Enable virtual threads for blocking I/O operations (spring.threads.virtual.enabled=true)

Java 21 Features:
- Use record classes for immutable data carriers (DTOs, configs, events)
- Use sealed interfaces for domain type hierarchies
- Use pattern matching with switch expressions for cleaner branching
- Use text blocks for SQL queries and templates
- Use SequencedCollection methods for ordered data access

Spring Data JPA:
- Use Spring Data repositories; avoid raw EntityManager unless necessary
- Define projections (interface-based or record-based) for read-only queries
- Use @EntityGraph to control eager/lazy loading per query
- Use Specification API for dynamic query building
- Always use @Transactional on service methods that write data
- Use Flyway or Liquibase for schema migrations; never hibernate.ddl-auto in production

Spring Security:
- Use SecurityFilterChain bean configuration (not WebSecurityConfigurerAdapter)
- Implement method-level security with @PreAuthorize
- Use BCryptPasswordEncoder for password hashing
- Configure CORS with explicit origins in CorsConfigurationSource
- Use OAuth2 Resource Server for JWT validation

Error Handling:
- Use @RestControllerAdvice for global exception handling
- Create domain-specific exception classes
- Return ProblemDetail (RFC 7807) for structured error responses
- Never expose stack traces or internal details in error responses

Testing:
- Use @SpringBootTest for integration tests with full context
- Use @WebMvcTest for controller-only tests with MockMvc
- Use @DataJpaTest for repository tests with embedded database
- Use Testcontainers for integration tests against real databases
- Use AssertJ for fluent, readable assertions

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

javaspring-bootjpaspring-securityvirtual-threadsrest-api