Spring Boot Cheat Sheet
A complete quick reference for Spring Boot 4.x (and 3.5) with Java 21/25. Covers every annotation, configuration property, testing shortcut, and CLI command you need in daily development.
Versions (November 2026)
| Line | Released | OSS support until | Notes |
|---|---|---|---|
| 4.1 (4.1.2) | Jun 2026 | Jul 2027 | Current. Spring Framework 7, Jakarta EE 11 |
| 4.0 | Nov 2025 | Dec 2026 | First 4.x: Jackson 3, modular starters, @MockitoBean only |
| 3.5 | May 2025 | ended Jun 2026 | Last 3.x — commercial support only. Upgrade path: latest 3.5.x → 4.0 → 4.1 |
Baseline: Java 17 minimum on both 3.x and 4.x (21 or 25 LTS recommended), jakarta.* packages (not javax.*) since 3.0, GraalVM 25+ for native images on 4.x.
Boot 3 → 4 changes you'll hit first
| Area | Boot 3.x | Boot 4.x |
|---|---|---|
| Web starter | spring-boot-starter-web | spring-boot-starter-webmvc (old name deprecated) |
| OAuth2 starters | spring-boot-starter-oauth2-* | spring-boot-starter-security-oauth2-* |
| AOP starter | spring-boot-starter-aop | spring-boot-starter-aspectj |
| Test deps | spring-boot-starter-test | per-technology test starters, e.g. spring-boot-starter-webmvc-test (pull in -test transitively) |
| Flyway / Liquibase | library on classpath | spring-boot-starter-flyway / spring-boot-starter-liquibase |
| Mocks in tests | @MockBean, @SpyBean (deprecated 3.4) | removed → @MockitoBean, @MockitoSpyBean |
| MockMvc / TestRestTemplate | provided by @SpringBootTest | add @AutoConfigureMockMvc / @AutoConfigureTestRestTemplate (or RestTestClient) |
| JSON | Jackson 2 (com.fasterxml.jackson) | Jackson 3 (tools.jackson; annotations keep com.fasterxml.jackson.annotation) |
| Jackson customizer | Jackson2ObjectMapperBuilderCustomizer, @JsonComponent | JsonMapperBuilderCustomizer, @JacksonComponent |
| HTTP client starters | part of starter-web | spring-boot-starter-restclient / spring-boot-starter-webclient |
| Embedded servers | Tomcat, Jetty, Undertow | Tomcat 11, Jetty 12.1 — Undertow removed |
| Health probes | opt-in | liveness/readiness enabled by default |
| Batch | JDBC metadata by default | starter-batch is in-memory; use spring-boot-starter-batch-jdbc |
| Migration aid | — | spring-boot-starter-classic / spring-boot-starter-test-classic, plus spring-boot-properties-migrator (runtime scope) |
Core Annotations
Application Setup
| Annotation | Purpose |
|---|---|
@SpringBootApplication | Entry point. Combines @Configuration + @EnableAutoConfiguration + @ComponentScan |
@EnableAutoConfiguration | Enable Spring Boot auto-configuration |
@ComponentScan | Scan for Spring components in current package and sub-packages |
@SpringBootConfiguration | Variant of @Configuration for Spring Boot |
Stereotype Annotations
| Annotation | Purpose | Special Behavior |
|---|---|---|
@Component | Generic Spring bean | None |
@Service | Business logic bean | None (semantic only) |
@Repository | Data access bean | Exception translation |
@Controller | Web MVC controller | View resolution |
@RestController | REST API controller | = @Controller + @ResponseBody |
@Configuration | Bean definition class | Proxied for singleton beans |
Dependency Injection
| Annotation | Purpose |
|---|---|
@Autowired | Inject dependency (optional with single constructor) |
@Qualifier("name") | Disambiguate between multiple beans |
@Primary | Preferred bean when multiple candidates |
@Value("${key}") | Inject property value |
@Lazy | Delay bean initialization until first use |
Bean Definition
| Annotation | Purpose |
|---|---|
@Bean | Declare a bean in @Configuration class |
@Scope("prototype") | Set bean scope (singleton/prototype/request/session) |
@Profile("dev") | Activate bean only in specific profile |
@ConditionalOnProperty | Create bean only if property is set |
@ConditionalOnClass | Create bean only if class exists on classpath |
@ConditionalOnMissingBean | Create bean only if no other bean of that type exists |
@ConfigurationProperties | Bind properties to a POJO/record |
Lifecycle
| Annotation | Purpose |
|---|---|
@PostConstruct | Run after dependency injection |
@PreDestroy | Run before bean destruction |
@EventListener | Handle application events |
@TransactionalEventListener | Handle events after transaction commit |
@Order(1) | Set bean initialization order |
Web Annotations
Request Mapping
| Annotation | HTTP Method |
|---|---|
@RequestMapping | Any (configurable) |
@GetMapping | GET |
@PostMapping | POST |
@PutMapping | PUT |
@PatchMapping | PATCH |
@DeleteMapping | DELETE |
Request Parameters
| Annotation | Source | Example |
|---|---|---|
@PathVariable | URL path | /users/{id} |
@RequestParam | Query string | ?name=foo&page=0 |
@RequestBody | Request body | JSON payload |
@RequestHeader | HTTP header | Authorization |
@CookieValue | Cookie | Session cookie |
@MatrixVariable | Matrix params | /cars;color=red |
Response
| Annotation | Purpose |
|---|---|
@ResponseBody | Serialize return value to response body |
@ResponseStatus(HttpStatus.CREATED) | Set HTTP status code |
@CrossOrigin | Enable CORS on controller/method |
@ExceptionHandler | Handle specific exception in controller |
@ControllerAdvice | Global exception handler |
@RestControllerAdvice | = @ControllerAdvice + @ResponseBody |
Validation Annotations
| Annotation | Validates |
|---|---|
@Valid | Cascading validation on @RequestBody or nested objects |
@Validated | Enables validation on path vars / request params; supports groups |
@NotNull | Not null |
@NotBlank | Not null, not empty, not whitespace (String) |
@NotEmpty | Not null, not empty (String/Collection) |
@Size(min, max) | String length or collection size |
@Min(value) | Numeric >= value |
@Max(value) | Numeric <= value |
@Positive | > 0 |
@PositiveOrZero | >= 0 |
@Email | Valid email format |
@Pattern(regexp) | Matches regex |
@Past / @Future | Date before/after now |
@DecimalMin / @DecimalMax | BigDecimal range |
@Digits(integer, fraction) | Number precision |
JPA Annotations
Entity Mapping
| Annotation | Purpose |
|---|---|
@Entity | JPA entity class |
@Table(name = "...") | Database table name |
@Id | Primary key |
@GeneratedValue | Auto-generated ID (UUID, IDENTITY, SEQUENCE) |
@Column | Column mapping (name, nullable, unique, length) |
@Enumerated(EnumType.STRING) | Enum stored as string |
@Lob | Large object (BLOB/CLOB) |
@Temporal | Date/time precision — only for legacy java.util.Date/Calendar; not needed (and not allowed) on java.time types |
@Version | Optimistic locking |
@CreationTimestamp | Auto-set on insert |
@UpdateTimestamp | Auto-set on update |
@Transient | Not persisted |
Relationships
| Annotation | Cardinality | Default Fetch |
|---|---|---|
@OneToOne | 1:1 | EAGER |
@OneToMany | 1:N | LAZY |
@ManyToOne | N:1 | EAGER (change to LAZY!) |
@ManyToMany | M:N | LAZY |
@JoinColumn | Foreign key column | — |
@JoinTable | Join table for M:N | — |
Repository
| Annotation | Purpose |
|---|---|
@Query("JPQL") | Custom JPQL query |
@Query(nativeQuery = true) | Native SQL query |
@Modifying | For UPDATE/DELETE queries |
@EntityGraph | Eager fetch specific associations |
@Lock(LockModeType.PESSIMISTIC_WRITE) | Pessimistic locking |
Security Annotations
| Annotation | Purpose |
|---|---|
@EnableWebSecurity | Enable Spring Security |
@EnableMethodSecurity | Enable @PreAuthorize/@PostAuthorize |
@PreAuthorize("expression") | Check before method execution |
@PostAuthorize("expression") | Check after method execution |
@Secured("ROLE_ADMIN") | Role-based access (simpler) |
@RolesAllowed("ADMIN") | Jakarta annotation for role check |
@AuthenticationPrincipal | Inject current user |
@WithMockUser | Test with fake user |
Testing Annotations
| Annotation | Loads | Speed |
|---|---|---|
@SpringBootTest | Full context | Slow |
@WebMvcTest(Controller.class) | Web slice | Fast |
@DataJpaTest | JPA slice | Medium |
@JsonTest | Jackson only | Fast |
@WebFluxTest | WebFlux slice | Fast |
@RestClientTest | RestClient / RestTemplate client slice with MockRestServiceServer | Fast |
@DataJdbcTest / @JdbcTest | Spring Data JDBC / JdbcClient slice | Medium |
| Annotation | Purpose |
|---|---|
@MockitoBean | Replace bean with Mockito mock (Spring Framework 6.2+; use this on Boot 3.4+ and 4.x) |
@MockitoSpyBean | Wrap bean with Mockito spy |
@MockBean / @SpyBean | Old names — deprecated in Boot 3.4, removed in 4.0 |
@AutoConfigureMockMvc | Add MockMvc to a @SpringBootTest (required on 4.x) |
@ServiceConnection | Wire a Testcontainers container to the app's connection properties (replaces most @DynamicPropertySource boilerplate) |
@ActiveProfiles("test") | Activate test profile |
@DynamicPropertySource | Set properties from Testcontainers |
@Sql("/data.sql") | Run SQL before test |
@Transactional | Rollback after each test |
@Testcontainers | Enable Testcontainers |
@Container | Mark Testcontainer field |
Caching Annotations
| Annotation | Purpose |
|---|---|
@EnableCaching | Enable cache abstraction |
@Cacheable(value, key) | Cache method result |
@CacheEvict(value, key) | Remove from cache |
@CachePut(value, key) | Always execute, update cache |
@Caching(...) | Combine multiple cache operations |
@CacheConfig(cacheNames) | Class-level cache defaults |
Async & Scheduling
| Annotation | Purpose |
|---|---|
@EnableAsync | Enable @Async support |
@Async | Run method in background thread |
@Async("executorName") | Use specific thread pool |
@EnableScheduling | Enable @Scheduled support |
@Scheduled(fixedRate = 5000) | Run every 5 seconds |
@Scheduled(cron = "0 0 2 * * *") | Run at 2 AM daily |
Common Configuration
application.yml Template
spring:
application:
name: my-app
profiles:
active: ${SPRING_PROFILES_ACTIVE:dev}
# Virtual threads (Java 21+): Tomcat/Jetty request handling, @Async, schedulers, JDK HttpClient
threads:
virtual:
enabled: true
# RFC 9457 problem+json error responses for MVC exceptions
mvc:
problemdetails:
enabled: true
# Database
datasource:
url: jdbc:postgresql://${DB_HOST:localhost}:5432/${DB_NAME:myapp}
username: ${DB_USERNAME:postgres}
password: ${DB_PASSWORD:postgres}
hikari:
maximum-pool-size: ${HIKARI_MAX_POOL:10}
minimum-idle: 5
connection-timeout: 30000
leak-detection-threshold: 60000
# JPA
jpa:
hibernate:
ddl-auto: validate
open-in-view: false
properties:
hibernate:
default_batch_fetch_size: 25
format_sql: true
jdbc.batch_size: 25
order_inserts: true
order_updates: true
# Jackson
jackson:
default-property-inclusion: non_null
serialization: # Boot 3.x (Jackson 2). Jackson 3 on Boot 4 already writes ISO-8601 dates;
write-dates-as-timestamps: false # Boot 4 moved read/write features to spring.jackson.json.read/write
# Flyway
flyway:
enabled: true
locations: classpath:db/migration
clean-disabled: true
# Server
server:
port: ${SERVER_PORT:8080}
shutdown: graceful
error:
include-message: always
include-binding-errors: always
# Actuator
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus
endpoint:
health:
show-details: when_authorized
probes:
enabled: true # default on Boot 4.x; needed on 3.x outside Kubernetes
# Logging
logging:
level:
root: WARN
com.example: INFO
org.hibernate.SQL: ${SQL_LOG_LEVEL:WARN}
pattern:
console: "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
Maven Commands
# Run application
./mvnw spring-boot:run
# Run with profile
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
# Run tests
./mvnw test
# Skip tests
./mvnw package -DskipTests
# Build JAR
./mvnw clean package
# Build native image
./mvnw -Pnative native:compile
# Build Docker image (Buildpacks)
./mvnw spring-boot:build-image
# Build Docker image (JIB)
./mvnw jib:dockerBuild
# Dependency tree
./mvnw dependency:tree
# Check for dependency updates
./mvnw versions:display-dependency-updates
# Generate project from Initializr
curl https://start.spring.io/starter.tgz \
-d type=maven-project -d language=java \
-d bootVersion=4.1.2 -d javaVersion=21 \
-d dependencies=web,data-jpa,postgresql,validation,actuator,lombok \
-d groupId=com.example -d artifactId=my-app | tar -xzvf -
Gradle Commands
# Run application
./gradlew bootRun
# Run with profile
SPRING_PROFILES_ACTIVE=dev ./gradlew bootRun
# Run tests
./gradlew test
# Build JAR
./gradlew bootJar
# Build native image
./gradlew nativeCompile
# Build Docker image
./gradlew bootBuildImage
# Dependency report
./gradlew dependencies --configuration runtimeClasspath
Actuator Endpoints
# Health check
curl http://localhost:8080/actuator/health
# Application info
curl http://localhost:8080/actuator/info
# List all metrics
curl http://localhost:8080/actuator/metrics
# Specific metric
curl http://localhost:8080/actuator/metrics/jvm.memory.used
# Prometheus format
curl http://localhost:8080/actuator/prometheus
# View log levels
curl http://localhost:8080/actuator/loggers/com.example
# Change log level at runtime
curl -X POST http://localhost:8080/actuator/loggers/com.example \
-H 'Content-Type: application/json' -d '{"configuredLevel":"DEBUG"}'
# Environment properties
curl http://localhost:8080/actuator/env
HTTP Status Code Quick Reference
| Code | Constant | When to Use |
|---|---|---|
| 200 | OK | Successful GET, PUT, PATCH |
| 201 | CREATED | Successful POST (resource created) |
| 204 | NO_CONTENT | Successful DELETE |
| 400 | BAD_REQUEST | Validation errors, malformed request |
| 401 | UNAUTHORIZED | Authentication required |
| 403 | FORBIDDEN | Authenticated but not authorized |
| 404 | NOT_FOUND | Resource does not exist |
| 409 | CONFLICT | Duplicate resource (e.g., duplicate email) |
| 422 | UNPROCESSABLE_ENTITY | Business rule violation |
| 429 | TOO_MANY_REQUESTS | Rate limit exceeded |
| 500 | INTERNAL_SERVER_ERROR | Unexpected server error |
| 502 | BAD_GATEWAY | External service error |
| 503 | SERVICE_UNAVAILABLE | Service temporarily down |
Common Spring Boot Starters
Boot 4 renames are shown as "3.x name → 4.x name"; the old names still work on 4.x but are deprecated.
| Starter | Includes |
|---|---|
spring-boot-starter-web → spring-boot-starter-webmvc | Spring MVC, Tomcat, Jackson |
spring-boot-starter-restclient (4.x) | RestClient, RestTemplate, HTTP service clients |
spring-boot-starter-data-jpa | Hibernate, HikariCP, Spring Data JPA |
spring-boot-starter-security | Spring Security |
spring-boot-starter-validation | Hibernate Validator |
spring-boot-starter-actuator | Health, metrics, info endpoints |
spring-boot-starter-cache | Caching abstraction |
spring-boot-starter-mail | Email sending |
spring-boot-starter-webflux | Reactive web (Netty) |
spring-boot-starter-data-redis | Redis client |
spring-boot-starter-oauth2-resource-server → spring-boot-starter-security-oauth2-resource-server | JWT validation |
spring-boot-starter-oauth2-client → spring-boot-starter-security-oauth2-client | OAuth2 login |
spring-boot-starter-test | JUnit, Mockito, MockMvc, AssertJ (on 4.x, add the per-technology -test starters, e.g. spring-boot-starter-webmvc-test) |
spring-boot-testcontainers | @ServiceConnection, Testcontainers at dev time |
spring-boot-docker-compose | Starts compose.yaml services on bootRun and wires connections |
spring-boot-starter-hateoas | HATEOAS links |
spring-boot-starter-batch | Batch processing |
Quick Patterns
Constructor Injection (Lombok)
@Service
@RequiredArgsConstructor // Generates constructor for final fields
public class OrderService {
private final OrderRepository orderRepository;
private final PaymentGateway paymentGateway;
}
Record DTO with Validation
public record CreateUserRequest(
@NotBlank @Email String email,
@NotBlank @Size(min = 8) String password,
@NotBlank String firstName
) {}
Paginated Endpoint
@GetMapping
public Page<ProductResponse> list(
@PageableDefault(size = 20, sort = "createdAt",
direction = Sort.Direction.DESC) Pageable pageable) {
return productService.findAll(pageable);
}
Global Exception Handler (Minimal)
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ProblemDetail handleNotFound(ResourceNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ProblemDetail handleAll(Exception ex) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
}
}
Typed Configuration (record)
import jakarta.validation.constraints.NotBlank; // jakarta.*, not javax.*
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "payments")
public record PaymentProperties(@NotBlank String apiUrl, Duration timeout, int maxRetries) {}
// Register: @ConfigurationPropertiesScan on the main class (or @EnableConfigurationProperties(PaymentProperties.class))
// application.yml: payments.api-url, payments.timeout: 5s, payments.max-retries: 3
RestClient (synchronous HTTP, Spring 6.1+ — preferred over RestTemplate for new code)
@Service
public class GitHubService {
private final RestClient restClient;
public GitHubService(RestClient.Builder builder) { // inject Boot's pre-configured builder
this.restClient = builder.baseUrl("https://api.github.com").build();
}
public Repo repo(String owner, String name) {
return restClient.get()
.uri("/repos/{owner}/{name}", owner, name)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (req, res) -> {
throw new RepoNotFoundException(owner + "/" + name);
})
.body(Repo.class);
}
public ResponseEntity<Void> create(NewRepo body) {
return restClient.post().uri("/user/repos").body(body).retrieve().toBodilessEntity();
}
}
HTTP Service Clients (declarative interface, Boot 4.x)
@HttpExchange("/repos")
public interface RepoClient {
@GetExchange("/{owner}/{name}")
Repo get(@PathVariable String owner, @PathVariable String name);
}
@SpringBootApplication
@ImportHttpServices(group = "github", types = RepoClient.class)
public class App { }
// application.yml: spring.http.serviceclient.github.base-url: https://api.github.com
// spring.http.serviceclient.github.read-timeout: 2s
On Boot 3.x, build the proxy yourself: HttpServiceProxyFactory.builderFor(RestClientAdapter.create(restClient)).build().createClient(RepoClient.class).
JdbcClient (lightweight SQL, Spring 6.1+)
List<User> users = jdbcClient.sql("SELECT id, email FROM users WHERE status = :status")
.param("status", "active")
.query(User.class) // maps columns to a record/bean
.list();
Testcontainers with @ServiceConnection
@SpringBootTest
@Testcontainers
class OrderRepositoryIT {
@Container
@ServiceConnection // sets spring.datasource.* automatically
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:18");
@MockitoBean PaymentGateway paymentGateway; // not @MockBean (removed in Boot 4)
}
Boot 4 manages Testcontainers 2.0, which reorganised module packages — let your IDE re-resolve the container import after upgrading.
Further Reading
- Spring Boot Overview — Getting started with Spring Boot
- Core Concepts — IoC, DI, and bean lifecycle
- REST API Development — Building production APIs
- Best Practices — Patterns and anti-patterns
- Virtual Threads — When
spring.threads.virtual.enabledhelps (and when it doesn't) - Testing — Slices, Testcontainers, MockMvc
- Migration Guide — Upgrading between major versions
Test Yourself
-
What annotation combines
@Controllerand@ResponseBody?@RestController -
How do you inject a property value from
application.ymlinto a field?@Value("${property.key}") -
What annotation activates a bean only in a specific profile?
@Profile("dev") -
What is the default fetch type for
@ManyToOnein JPA, and why is it problematic? EAGER -- it loads the related entity on every query, causing N+1 problems. Change tofetch = FetchType.LAZY. -
What test slice annotation loads only the web layer for a specific controller?
@WebMvcTest(Controller.class) -
How do you change the log level of a package at runtime via Actuator?
curl -X POST .../actuator/loggers/com.example -H 'Content-Type: application/json' -d '{"configuredLevel":"DEBUG"}' -
What annotation creates a bean only if no other bean of that type exists (the way auto-configuration backs off)?
@ConditionalOnMissingBean. (To create a bean only when another bean does exist, use@ConditionalOnBean; to force initialization order, use@DependsOn.) -
What HTTP status should a successful POST that creates a resource return?
201 CREATED -
How do you build a Docker image from a Spring Boot project using Buildpacks?
./mvnw spring-boot:build-image -
What annotation enables method-level security like
@PreAuthorize?@EnableMethodSecurity
Common Gotchas
spring.jpa.open-in-view=true(default). It keeps the Hibernate session open during the entire HTTP request, which hides lazy loading issues in development but causes performance problems in production. Set it tofalse.@ManyToOnedefaults to EAGER fetch. Every time you load an entity, JPA also loads the related entity. Always setfetch = FetchType.LAZYon@ManyToOne.- Using
@Autowiredon fields instead of constructor injection. Field injection makes testing harder and hides dependencies. Use@RequiredArgsConstructorwithfinalfields. ddl-auto=updatein production. Hibernate's schema auto-update can drop columns or create wrong indexes. Usevalidatein production with Flyway or Liquibase for migrations.javax.*imports after upgrading. Boot 3+ usesjakarta.persistence,jakarta.validation,jakarta.servlet; mixed imports compile against the wrong API or fail at startup.@MockBeanon Boot 4. It's removed — switch to@MockitoBean/@MockitoSpyBean(they can't be declared in@Configurationclasses).- Virtual threads +
synchronized+ blocking I/O. Pinning was largely fixed in Java 24 (JEP 491), but on Java 21 longsynchronizedblocks around I/O pin carrier threads — preferReentrantLock, and remember a bigger thread count doesn't enlarge your DB pool. @Transactionalon private methods or self-invocation. Spring's proxy only intercepts public calls from another bean; callingthis.save()skips the transaction.server.error.include-message: alwaysin production can leak internal details; restrict it to dev profiles.
One-Liner Summary
Spring Boot is an opinionated Java framework that auto-configures everything -- master annotations, profiles, Actuator, and test slices to build production-ready APIs with minimal boilerplate.