Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 66 ยท Practice and Review

Spring Boot Cheat Sheet

A one-page Spring Boot cheat sheet: annotations, application properties, starters, test annotations, Actuator endpoints, status codes and everyday build commands.

This page puts the whole Spring Boot course on one screen: the annotations you type every day, the properties you look up every week, the starters, test annotations, Actuator endpoints and build commands. It is built for scanning while you code, before a code review or before an interview. Every table points back to the lesson that explains the topic properly, so use it as an index as well as a reminder.

Spring Boot cannot run on this site, so all framework code and configuration is read-only. Two live helpers cover the two things people most often get wrong from memory: how a property name maps to an environment variable, and what a Spring cron expression actually means. Both are small plain-Java stand-ins that follow the documented rules. Versions follow the course: Java 17 or later (examples use 25), Spring Boot 3 and 4, Spring Framework 6.2 and 7, Jakarta EE namespaces (jakarta.*).

What is on this page

Annotations Beans, web, data, security, tests.
Properties The settings you look up weekly.
Starters Which dependency gives what.
Actuator Endpoints and how to expose them.
1 / 2

Core annotations

Annotation Where What it does
@SpringBootApplication main class @Configuration + @EnableAutoConfiguration + @ComponentScan of its package and below
@Component, @Service, @Repository class Register a bean by scanning; @Repository also translates persistence exceptions
@Configuration class Holds @Bean methods
@Bean method Returns an object to register; name = method name
@Autowired constructor, field Inject a dependency (optional on a single constructor)
@Primary bean The default choice among several candidates
@Qualifier("name") parameter, bean Pick a specific candidate
@Scope("prototype") bean New instance per request for the bean
@Lazy bean, injection Create on first use
@PostConstruct, @PreDestroy method Run after construction / before shutdown
@Profile("dev") bean, config class Only when the profile is active
@Value("${key:default}") field, parameter Inject one property value
@ConfigurationProperties("app.x") class, record Bind a group of properties to a typed object
@EventListener method React to an application event
@Scheduled, @Async, @EnableScheduling, @EnableAsync method / config Scheduled and asynchronous work

Lessons: IoC and Dependency Injection, Component Scanning and Stereotypes, @Configuration and @Bean, Bean Scopes and Lifecycle, Qualifiers, @Primary and Collections.

Conditions (auto-configuration)

Annotation Bean is created when...
@ConditionalOnClass / OnMissingClass a class is (not) on the classpath
@ConditionalOnBean / OnMissingBean a bean of that type is (not) already defined; OnMissingBean makes your own bean win
@ConditionalOnProperty(name, havingValue, matchIfMissing) a property has a value
@ConditionalOnWebApplication the app is a servlet or reactive web app
@ConditionalOnExpression, @ConditionalOnResource, @ConditionalOnCloudPlatform an SpEL expression is true, a file exists, a platform is detected

Register your own auto-configuration in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. See Conditional Beans and How Auto-Configuration Works.

Web and REST annotations

Java
@RestController
@RequestMapping("/books")
public class BookController {

    @GetMapping                          // GET /books?page=0&size=20
    Page<BookDto> list(@PageableDefault(size = 20) Pageable pageable) { ... }

    @GetMapping("/{id}")                 // GET /books/7
    BookDto get(@PathVariable long id) { ... }

    @PostMapping                         // POST /books, JSON body
    ResponseEntity<BookDto> create(@Valid @RequestBody CreateBook body) {
        return ResponseEntity.created(URI.create("/books/" + saved.id())).body(saved);
    }

    @PutMapping("/{id}")    BookDto replace(@PathVariable long id, @Valid @RequestBody CreateBook body) { ... }
    @PatchMapping("/{id}")  BookDto update(@PathVariable long id, @RequestBody Map<String, Object> patch) { ... }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void delete(@PathVariable long id) { ... }
}
Annotation Purpose
@RequestParam Query parameter or form field (required, defaultValue)
@RequestHeader, @CookieValue Read a header or cookie
@RequestBody / @ResponseBody Convert the body with Jackson (@RestController implies @ResponseBody)
@ResponseStatus Fixed status for a method or an exception class
@Valid, @Validated Trigger validation; @Validated adds groups and method validation
@RestControllerAdvice + @ExceptionHandler Global error mapping, return ProblemDetail
@CrossOrigin Per-controller CORS (prefer central configuration)

Common constraints: @NotNull, @NotBlank (strings), @NotEmpty (collections), @Size(min, max), @Min, @Max, @Positive, @Email, @Pattern(regexp), @Past, @Future. Lessons: REST Controllers, Bean Validation, Error Handling and Problem Details, Filters, Interceptors and Argument Resolvers.

HTTP status codes for APIs

Situation Status
Successful read or update returning a body 200 OK
Created (with a Location header) 201 Created
Success, nothing to return (delete, some updates) 204 No Content
Malformed JSON, failed validation 400 Bad Request (or 422)
Not logged in 401 Unauthorized
Logged in but not allowed 403 Forbidden
Unknown resource or path 404 Not Found
Path exists, method does not 405 Method Not Allowed
Duplicate or stale version 409 Conflict
Wrong Content-Type for the body 415 Unsupported Media Type
Too many requests 429 Too Many Requests
Unhandled server fault 500 Internal Server Error
Dependency down 503 Service Unavailable

Data annotations

Annotation Purpose
@Entity, @Table(name), @Id, @GeneratedValue Map a class to a table and its key
@Column(nullable, length, unique) Column settings (documentation when Flyway owns the schema)
@Enumerated(EnumType.STRING) Store enums by name, never by ordinal
@OneToMany(mappedBy), @ManyToOne(fetch = LAZY), @ManyToMany Relationships; the side with @JoinColumn owns the foreign key
@Version Optimistic locking
@Query, @Modifying, @Param Custom JPQL or native query; @Modifying for updates and deletes
@EntityGraph(attributePaths = ...) Fetch associations in the same query (N+1 fix)
@Transactional Transaction around a method; rolls back on runtime exceptions by default
@TransactionalEventListener(phase = AFTER_COMMIT) Listener that runs only after a successful commit
@Cacheable, @CacheEvict, @CachePut, @EnableCaching Declarative caching

Repository methods derive queries from names: findByEmail, findByAuthorNameOrderByTitleAsc, existsByIsbn, countByStatus, deleteByCreatedAtBefore, and findTop5ByOrderByCreatedAtDesc. Keywords: And, Or, Between, LessThan, Like, StartingWith, Containing, In, IsNull, OrderBy. Lessons: Spring Data JPA Repositories, Entity Relationships and the N+1 Problem, Transactions with @Transactional, Caching.

Security annotations and configuration

Java
@Configuration
@EnableMethodSecurity
class SecurityConfig {
    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())                       // only for stateless, token-based APIs
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(a -> a
                .requestMatchers("/actuator/health/**").permitAll()
                .requestMatchers(HttpMethod.GET, "/books/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
            .build();
    }

    @Bean
    PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); }
}

Rules are matched top to bottom, first match wins. Method security: @PreAuthorize("hasRole('ADMIN')"), @PreAuthorize("#id == authentication.principal.id"), @PostAuthorize, @Secured. In tests: @WithMockUser(roles = "ADMIN"). Lessons: Spring Security Fundamentals, JWT and OAuth 2 Resource Server, CSRF, CORS and Secure Defaults.

Properties you look up often

Property Meaning
spring.application.name Service name in logs, metrics and tracing
server.port HTTP port (0 = random free port)
server.servlet.context-path Prefix for every URL
server.shutdown=graceful Finish in-flight requests on shutdown
spring.lifecycle.timeout-per-shutdown-phase How long to wait (for example 30s)
server.compression.enabled Compress responses
spring.profiles.active Active profiles, comma-separated
spring.config.import Load more config (optional:file:./local.yml, configtree:/run/secrets/)
spring.datasource.url / username / password Database connection
spring.datasource.hikari.maximum-pool-size Connection pool size (default 10)
spring.jpa.hibernate.ddl-auto none, validate (with Flyway), create-drop (tests only)
spring.jpa.open-in-view Default true; false is the usual advice
spring.jpa.show-sql Print SQL (better: logging.level.org.hibernate.SQL=DEBUG)
spring.flyway.enabled / locations Migrations (default classpath:db/migration)
spring.jackson.default-property-inclusion For example non_null
spring.mvc.problemdetails.enabled Standard errors as Problem Details
spring.servlet.multipart.max-file-size Upload limits
spring.data.web.pageable.max-page-size Cap for the size parameter
spring.threads.virtual.enabled Virtual threads (Java 21+)
spring.main.lazy-initialization Create beans on first use (delays wiring errors)
spring.cache.type caffeine, redis, simple, none
logging.level.<package> Log level, for example logging.level.com.example=DEBUG
management.endpoints.web.exposure.include Which Actuator endpoints are on the web
management.endpoint.health.probes.enabled Liveness and readiness groups
debug=true Print the auto-configuration conditions report

Lessons: Properties, YAML and Externalized Config, Profiles and Environment-Specific Config, Logging, Database Migrations with Flyway.

Property names and environment variables

Boot reads one property from many spellings (relaxed binding). The canonical form in application.properties is lower-case kebab-case; environment variables use upper-case with underscores. The conversion for an environment variable is: dots become underscores, dashes are removed, everything is upper-cased, and list indexes become numbers. Edit the list of keys below and run it.

Java Property name to environment variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output closely: app.mail.retry-count becomes APP_MAIL_RETRYCOUNT (the dash disappears) and app.servers[0].host becomes APP_SERVERS_0_HOST. In YAML or .properties files you may write either retry-count or retryCount; for new code, prefer kebab-case.

Starters

Starter Gives you
spring-boot-starter-web Spring MVC, Jackson, embedded Tomcat
spring-boot-starter-webflux Reactive web stack with Netty
spring-boot-starter-validation Bean Validation with Hibernate Validator
spring-boot-starter-data-jpa Hibernate, Spring Data JPA, connection pool
spring-boot-starter-jdbc JDBC, JdbcClient, HikariCP
spring-boot-starter-data-redis, -data-mongodb Redis and MongoDB support
spring-boot-starter-security Spring Security
spring-boot-starter-oauth2-resource-server JWT and opaque token validation
spring-boot-starter-actuator Health, metrics and management endpoints
spring-boot-starter-cache Cache abstraction
spring-boot-starter-thymeleaf Server-side HTML templates
spring-boot-starter-test JUnit, AssertJ, Mockito, Spring Test
spring-boot-devtools Restart on change, LiveReload (development only)

Flyway, Liquibase, Testcontainers and database drivers are added as ordinary dependencies; Boot's BOM manages their versions. See Starters and Dependency Management.

Test annotations

Annotation Loads Typical use
@SpringBootTest Full context (webEnvironment = RANDOM_PORT starts a server) End-to-end wiring checks
@WebMvcTest(BookController.class) MVC layer only Controller tests with MockMvc
@DataJpaTest Entities and repositories, transactional rollback Repository and query tests
@JsonTest Jackson only Serialization contracts
@RestClientTest RestClient beans and a mock server HTTP client tests
@AutoConfigureMockMvc Adds MockMvc to a full context Web tests with real beans
@MockitoBean, @MockitoSpyBean Replace or wrap a bean with a Mockito object Isolate a layer
@TestConfiguration, @Import Extra beans for a test Fakes and helpers
@ActiveProfiles("test"), @TestPropertySource Profile and properties Test settings
@ServiceConnection Wire a Testcontainers container into Boot Real database in tests
@DynamicPropertySource Properties computed at test time Container ports and URLs
@Sql, @DirtiesContext Run scripts / discard the cached context (expensive) Use sparingly
@WithMockUser A fake authenticated user Security tests

Lessons: Testing Spring Boot Applications, Testing Controllers with MockMvc, Integration Tests with Testcontainers, Test Slices, Context Caching and Test Speed.

Actuator endpoints

Only health is exposed on the web by default. Expose others deliberately:

YAML
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus
  endpoint:
    health:
      show-details: when-authorized
      probes:
        enabled: true
Endpoint Shows Sensitive?
health (/health/liveness, /health/readiness) Up or down, probes for Kubernetes Details only to authorized users
info Build, git and custom info Low
metrics, prometheus Micrometer meters (the latter needs micrometer-registry-prometheus) Medium
loggers Read and change log levels at runtime High (it is writable)
env, configprops Properties and their sources High: may contain secrets
beans, conditions, mappings Context, auto-configuration decisions, URL mappings Medium
threaddump, heapdump JVM diagnostics High: memory contents
scheduledtasks, caches, flyway Jobs, caches, migrations Low to medium

Lessons: Actuator: Health, Metrics and Info, Observability: Metrics, Tracing and Logs.

Cron expressions for @Scheduled

@Scheduled(cron = "0 0 9 * * MON-FRI") takes six fields, not five like Unix cron: second, minute, hour, day of month, month, day of week. * means every value, */15 every 15th, 1-5 a range, 1,15 a list; weekdays can be MON to SUN, and 0 or 7 is Sunday. Spring requires day of month and day of week to both match when you restrict both. Other styles: fixedDelay (wait after the previous run ends), fixedRate (start at fixed intervals) and zone = "Europe/Berlin" to pick the time zone.

The helper below expands each field and walks forward from a fixed start time, so you can check what an expression really does. It supports numbers, *, */n, ranges, lists and weekday names; Spring's parser accepts more (such as L, W, # and macros like @daily).

Java When does this cron expression fire?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The weekday expression skips the weekend, so the first run after Sunday is Monday 09:00; the quarter-hour expression fires at minute 15, 30 and 45; the monthly one fires at 02:30 on the first day of each month. More on scheduling in Scheduling and Asynchronous Work.

Everyday commands

Terminal
# Maven wrapper
./mvnw spring-boot:run                       # run in development
./mvnw clean verify                          # build + tests
./mvnw -DskipTests package                   # executable jar in target/
./mvnw spring-boot:build-image               # OCI image with Cloud Native Buildpacks
./mvnw dependency:tree                       # find version conflicts

# Gradle wrapper
./gradlew bootRun
./gradlew bootJar                            # executable jar in build/libs/
./gradlew bootBuildImage
./gradlew dependencies

# Running the jar
java -jar app.jar --server.port=9090 --spring.profiles.active=prod
SPRING_PROFILES_ACTIVE=prod DB_PASSWORD=... java -jar app.jar
java -jar app.jar --debug                    # conditions report
java -Djarmode=tools -jar app.jar extract --layers --launcher   # layered output for Docker

# Quick checks
curl -i http://localhost:8080/actuator/health
curl -i -X POST http://localhost:8080/books -H 'Content-Type: application/json' -d '{"title":"Dune"}'

Lessons: Building and Running the Jar, Containers: Dockerfile and Buildpacks, Deployment: Cloud, Kubernetes and Config.

Rules of thumb

  • Constructor injection, immutable fields, one reason to change per class.
  • Never expose entities; return records as DTOs and map inside the service.
  • Fail fast: validate input at the edge and configuration at startup (@Validated properties, ddl-auto: validate).
  • Keep transactions short and on the service layer; remember proxies skip self-calls.
  • Secrets come from the environment or a secret store, never from the repository.
  • When something surprising happens, run with --debug and read the last Caused by:; see Common Mistakes and Debugging Startup Failures.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which environment variable sets app.mail.retry-count?

    Dots become underscores, dashes are removed and the name is upper-cased. The live converter above prints exactly this.
  2. 2. How many fields does a Spring cron expression for @Scheduled have?

    Spring's order is second, minute, hour, day of month, month, day of week.
  3. 3. Which Actuator endpoint is exposed over HTTP by default?

    Only health is on the web by default; everything else must be listed in management.endpoints.web.exposure.include, and sensitive ones secured.
  4. 4. Which test annotation loads only controllers and the MVC infrastructure?

    @WebMvcTest is the web-layer slice; services must be provided with @MockitoBean or @Import.

Summary

  • Annotations: scan with stereotypes, define third-party beans with @Bean, choose candidates with @Primary and @Qualifier, bind settings with @ConfigurationProperties.
  • Web: pick the mapping annotation, validate with @Valid, map errors in one @RestControllerAdvice and use the right status code.
  • Data: derive queries from names, fix N+1 with fetch joins, keep @Transactional on services and the schema in Flyway scripts.
  • Properties map to environment variables by dropping dashes and using underscores; Spring cron has six fields with seconds first.
  • Test with slices first, expose only the Actuator endpoints you need and debug with --debug.

You have reached the end of the Spring Boot course. Rebuild a project such as Project: Todo REST API from memory, keep this sheet and Spring Boot Interview Questions at hand, and return to the Spring Boot course overview whenever you want to review a topic.