On this page

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)

LineReleasedOSS support untilNotes
4.1 (4.1.2)Jun 2026Jul 2027Current. Spring Framework 7, Jakarta EE 11
4.0Nov 2025Dec 2026First 4.x: Jackson 3, modular starters, @MockitoBean only
3.5May 2025ended Jun 2026Last 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

AreaBoot 3.xBoot 4.x
Web starterspring-boot-starter-webspring-boot-starter-webmvc (old name deprecated)
OAuth2 startersspring-boot-starter-oauth2-*spring-boot-starter-security-oauth2-*
AOP starterspring-boot-starter-aopspring-boot-starter-aspectj
Test depsspring-boot-starter-testper-technology test starters, e.g. spring-boot-starter-webmvc-test (pull in -test transitively)
Flyway / Liquibaselibrary on classpathspring-boot-starter-flyway / spring-boot-starter-liquibase
Mocks in tests@MockBean, @SpyBean (deprecated 3.4)removed → @MockitoBean, @MockitoSpyBean
MockMvc / TestRestTemplateprovided by @SpringBootTestadd @AutoConfigureMockMvc / @AutoConfigureTestRestTemplate (or RestTestClient)
JSONJackson 2 (com.fasterxml.jackson)Jackson 3 (tools.jackson; annotations keep com.fasterxml.jackson.annotation)
Jackson customizerJackson2ObjectMapperBuilderCustomizer, @JsonComponentJsonMapperBuilderCustomizer, @JacksonComponent
HTTP client starterspart of starter-webspring-boot-starter-restclient / spring-boot-starter-webclient
Embedded serversTomcat, Jetty, UndertowTomcat 11, Jetty 12.1 — Undertow removed
Health probesopt-inliveness/readiness enabled by default
BatchJDBC metadata by defaultstarter-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

AnnotationPurpose
@SpringBootApplicationEntry point. Combines @Configuration + @EnableAutoConfiguration + @ComponentScan
@EnableAutoConfigurationEnable Spring Boot auto-configuration
@ComponentScanScan for Spring components in current package and sub-packages
@SpringBootConfigurationVariant of @Configuration for Spring Boot

Stereotype Annotations

AnnotationPurposeSpecial Behavior
@ComponentGeneric Spring beanNone
@ServiceBusiness logic beanNone (semantic only)
@RepositoryData access beanException translation
@ControllerWeb MVC controllerView resolution
@RestControllerREST API controller= @Controller + @ResponseBody
@ConfigurationBean definition classProxied for singleton beans

Dependency Injection

AnnotationPurpose
@AutowiredInject dependency (optional with single constructor)
@Qualifier("name")Disambiguate between multiple beans
@PrimaryPreferred bean when multiple candidates
@Value("${key}")Inject property value
@LazyDelay bean initialization until first use

Bean Definition

AnnotationPurpose
@BeanDeclare a bean in @Configuration class
@Scope("prototype")Set bean scope (singleton/prototype/request/session)
@Profile("dev")Activate bean only in specific profile
@ConditionalOnPropertyCreate bean only if property is set
@ConditionalOnClassCreate bean only if class exists on classpath
@ConditionalOnMissingBeanCreate bean only if no other bean of that type exists
@ConfigurationPropertiesBind properties to a POJO/record

Lifecycle

AnnotationPurpose
@PostConstructRun after dependency injection
@PreDestroyRun before bean destruction
@EventListenerHandle application events
@TransactionalEventListenerHandle events after transaction commit
@Order(1)Set bean initialization order

Web Annotations

Request Mapping

AnnotationHTTP Method
@RequestMappingAny (configurable)
@GetMappingGET
@PostMappingPOST
@PutMappingPUT
@PatchMappingPATCH
@DeleteMappingDELETE

Request Parameters

AnnotationSourceExample
@PathVariableURL path/users/{id}
@RequestParamQuery string?name=foo&page=0
@RequestBodyRequest bodyJSON payload
@RequestHeaderHTTP headerAuthorization
@CookieValueCookieSession cookie
@MatrixVariableMatrix params/cars;color=red

Response

AnnotationPurpose
@ResponseBodySerialize return value to response body
@ResponseStatus(HttpStatus.CREATED)Set HTTP status code
@CrossOriginEnable CORS on controller/method
@ExceptionHandlerHandle specific exception in controller
@ControllerAdviceGlobal exception handler
@RestControllerAdvice= @ControllerAdvice + @ResponseBody

Validation Annotations

AnnotationValidates
@ValidCascading validation on @RequestBody or nested objects
@ValidatedEnables validation on path vars / request params; supports groups
@NotNullNot null
@NotBlankNot null, not empty, not whitespace (String)
@NotEmptyNot 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
@EmailValid email format
@Pattern(regexp)Matches regex
@Past / @FutureDate before/after now
@DecimalMin / @DecimalMaxBigDecimal range
@Digits(integer, fraction)Number precision

JPA Annotations

Entity Mapping

AnnotationPurpose
@EntityJPA entity class
@Table(name = "...")Database table name
@IdPrimary key
@GeneratedValueAuto-generated ID (UUID, IDENTITY, SEQUENCE)
@ColumnColumn mapping (name, nullable, unique, length)
@Enumerated(EnumType.STRING)Enum stored as string
@LobLarge object (BLOB/CLOB)
@TemporalDate/time precision — only for legacy java.util.Date/Calendar; not needed (and not allowed) on java.time types
@VersionOptimistic locking
@CreationTimestampAuto-set on insert
@UpdateTimestampAuto-set on update
@TransientNot persisted

Relationships

AnnotationCardinalityDefault Fetch
@OneToOne1:1EAGER
@OneToMany1:NLAZY
@ManyToOneN:1EAGER (change to LAZY!)
@ManyToManyM:NLAZY
@JoinColumnForeign key column—
@JoinTableJoin table for M:N—

Repository

AnnotationPurpose
@Query("JPQL")Custom JPQL query
@Query(nativeQuery = true)Native SQL query
@ModifyingFor UPDATE/DELETE queries
@EntityGraphEager fetch specific associations
@Lock(LockModeType.PESSIMISTIC_WRITE)Pessimistic locking

Security Annotations

AnnotationPurpose
@EnableWebSecurityEnable Spring Security
@EnableMethodSecurityEnable @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
@AuthenticationPrincipalInject current user
@WithMockUserTest with fake user

Testing Annotations

AnnotationLoadsSpeed
@SpringBootTestFull contextSlow
@WebMvcTest(Controller.class)Web sliceFast
@DataJpaTestJPA sliceMedium
@JsonTestJackson onlyFast
@WebFluxTestWebFlux sliceFast
@RestClientTestRestClient / RestTemplate client slice with MockRestServiceServerFast
@DataJdbcTest / @JdbcTestSpring Data JDBC / JdbcClient sliceMedium
AnnotationPurpose
@MockitoBeanReplace bean with Mockito mock (Spring Framework 6.2+; use this on Boot 3.4+ and 4.x)
@MockitoSpyBeanWrap bean with Mockito spy
@MockBean / @SpyBeanOld names — deprecated in Boot 3.4, removed in 4.0
@AutoConfigureMockMvcAdd MockMvc to a @SpringBootTest (required on 4.x)
@ServiceConnectionWire a Testcontainers container to the app's connection properties (replaces most @DynamicPropertySource boilerplate)
@ActiveProfiles("test")Activate test profile
@DynamicPropertySourceSet properties from Testcontainers
@Sql("/data.sql")Run SQL before test
@TransactionalRollback after each test
@TestcontainersEnable Testcontainers
@ContainerMark Testcontainer field

Caching Annotations

AnnotationPurpose
@EnableCachingEnable 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

AnnotationPurpose
@EnableAsyncEnable @Async support
@AsyncRun method in background thread
@Async("executorName")Use specific thread pool
@EnableSchedulingEnable @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

CodeConstantWhen to Use
200OKSuccessful GET, PUT, PATCH
201CREATEDSuccessful POST (resource created)
204NO_CONTENTSuccessful DELETE
400BAD_REQUESTValidation errors, malformed request
401UNAUTHORIZEDAuthentication required
403FORBIDDENAuthenticated but not authorized
404NOT_FOUNDResource does not exist
409CONFLICTDuplicate resource (e.g., duplicate email)
422UNPROCESSABLE_ENTITYBusiness rule violation
429TOO_MANY_REQUESTSRate limit exceeded
500INTERNAL_SERVER_ERRORUnexpected server error
502BAD_GATEWAYExternal service error
503SERVICE_UNAVAILABLEService 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.

StarterIncludes
spring-boot-starter-web → spring-boot-starter-webmvcSpring MVC, Tomcat, Jackson
spring-boot-starter-restclient (4.x)RestClient, RestTemplate, HTTP service clients
spring-boot-starter-data-jpaHibernate, HikariCP, Spring Data JPA
spring-boot-starter-securitySpring Security
spring-boot-starter-validationHibernate Validator
spring-boot-starter-actuatorHealth, metrics, info endpoints
spring-boot-starter-cacheCaching abstraction
spring-boot-starter-mailEmail sending
spring-boot-starter-webfluxReactive web (Netty)
spring-boot-starter-data-redisRedis client
spring-boot-starter-oauth2-resource-server → spring-boot-starter-security-oauth2-resource-serverJWT validation
spring-boot-starter-oauth2-client → spring-boot-starter-security-oauth2-clientOAuth2 login
spring-boot-starter-testJUnit, 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-composeStarts compose.yaml services on bootRun and wires connections
spring-boot-starter-hateoasHATEOAS links
spring-boot-starter-batchBatch 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


Test Yourself
  1. What annotation combines @Controller and @ResponseBody? @RestController

  2. How do you inject a property value from application.yml into a field? @Value("${property.key}")

  3. What annotation activates a bean only in a specific profile? @Profile("dev")

  4. What is the default fetch type for @ManyToOne in JPA, and why is it problematic? EAGER -- it loads the related entity on every query, causing N+1 problems. Change to fetch = FetchType.LAZY.

  5. What test slice annotation loads only the web layer for a specific controller? @WebMvcTest(Controller.class)

  6. 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"}'

  7. 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.)

  8. What HTTP status should a successful POST that creates a resource return? 201 CREATED

  9. How do you build a Docker image from a Spring Boot project using Buildpacks? ./mvnw spring-boot:build-image

  10. 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 to false.
  • @ManyToOne defaults to EAGER fetch. Every time you load an entity, JPA also loads the related entity. Always set fetch = FetchType.LAZY on @ManyToOne.
  • Using @Autowired on fields instead of constructor injection. Field injection makes testing harder and hides dependencies. Use @RequiredArgsConstructor with final fields.
  • ddl-auto=update in production. Hibernate's schema auto-update can drop columns or create wrong indexes. Use validate in production with Flyway or Liquibase for migrations.
  • javax.* imports after upgrading. Boot 3+ uses jakarta.persistence, jakarta.validation, jakarta.servlet; mixed imports compile against the wrong API or fail at startup.
  • @MockBean on Boot 4. It's removed — switch to @MockitoBean / @MockitoSpyBean (they can't be declared in @Configuration classes).
  • Virtual threads + synchronized + blocking I/O. Pinning was largely fixed in Java 24 (JEP 491), but on Java 21 long synchronized blocks around I/O pin carrier threads — prefer ReentrantLock, and remember a bigger thread count doesn't enlarge your DB pool.
  • @Transactional on private methods or self-invocation. Spring's proxy only intercepts public calls from another bean; calling this.save() skips the transaction.
  • server.error.include-message: always in 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.