BE·47
Spring Boot
What Spring Boot adds on top of Spring: auto-configuration and how conditions decide what's wired, starters, type-safe configuration properties and externalised configuration precedence, profiles, embedded servers, Actuator with health, readiness and liveness, metrics and tracing via Micrometer and OpenTelemetry, graceful shutdown, test slices, AOT processing, native images, CDS and container images. Compared with Quarkus, Micronaut, ASP.NET Core's host, NestJS, Phoenix, and the assemble-it-yourself style of Go and Rust services.
Start here: a production-shaped service in one class
What Boot adds to Spring
Plain Spring gives you a container; you still choose and configure a web server, a JSON library, logging, a connection pool and dozens of settings, and wire them all together. Spring Boot does that for you with three ideas:
- Starters: one dependency per capability (
spring-boot-starter-webmvc,-data-jpa,-security,-actuator) that brings a tested, version-aligned set of libraries. - Auto-configuration: hundreds of
@Configurationclasses that create sensible beans only if the relevant library is on the classpath and you haven't defined your own. Add the web starter and you get an embedded Tomcat, Spring MVC and a JacksonJsonMapper, with no code. - Externalised configuration: settings come from
application.properties, profile-specific files, environment variables and command-line arguments, bound to typed objects.
The result is a runnable JAR containing its own web server (java -jar app.jar), which is how almost every Spring service is now built and deployed. Quarkus, Micronaut and Helidon (JVM), ASP.NET Core, NestJS, Django and Rails follow the same "conventions with escape hatches" approach.
The whole application
@SpringBootApplication
@ConfigurationPropertiesScan
public class CafeApplication {
public static void main(String[] args) { SpringApplication.run(CafeApplication.class, args); }
@ConfigurationProperties("cafe")
public record CafeProperties(String name, int gstPercent, Duration kitchenTimeout, List<String> openDays) {}
public record Dish(int id, String name, long pricePaise) {}
@RestController
static class MenuController {
private final CafeProperties props;
MenuController(CafeProperties props) { this.props = props; }
@GetMapping("/menu") Map<String, Object> menu() {
return Map.of("cafe", props.name(), "gstPercent", props.gstPercent(), "kitchenTimeoutSeconds", props.kitchenTimeout().toSeconds(),
"openDays", props.openDays(), "dishes", List.of(new Dish(1, "Masala dosa", 9000), new Dish(2, "Filter coffee", 3000)));
}
}
}
# application.properties
spring.application.name=cafe
server.port=8094
cafe.name=Udupi Corner
cafe.gst-percent=5
cafe.kitchen-timeout=45s
cafe.open-days=MON,TUE,WED,THU,FRI,SAT
# application-prod.properties (used only when the prod profile is active)
cafe.gst-percent=18
server.port=8095
$ java -jar cafe.jar
Starting CafeApplication using Java 21.0.12.1 with PID 5300
No active profile set, falling back to 1 default profile: "default"
Starting Servlet engine: [Apache Tomcat/11.0.24]
Tomcat started on port 8094 (http) with context path '/'
Started CafeApplication in 2.313 seconds (process running for 2.677)
$ curl localhost:8094/menu
{"cafe":"Udupi Corner","dishes":[{"id":1,"name":"Masala dosa","pricePaise":9000},{"id":2,"name":"Filter coffee","pricePaise":3000}],
"gstPercent":5,"kitchenTimeoutSeconds":45,"openDays":["MON","TUE","WED","THU","FRI","SAT"]}
There's no server setup, JSON code or wiring in the source. @SpringBootApplication turned on component scanning and auto-configuration; auto-configuration saw Tomcat, Spring MVC and Jackson on the classpath and set them up; the controller's return value (records and a map) was serialised to JSON by Jackson. @ConfigurationProperties bound every cafe.* property to a typed record: 45s became a Duration, the comma list a List<String>, kebab-case gst-percent the field gstPercent.
Same build, different environment
$ CAFE_NAME="Udupi Corner (Airport)" java -jar cafe.jar --spring.profiles.active=prod --cafe.kitchen-timeout=2m
The following 1 profile is active: "prod"
Tomcat started on port 8095 (http) with context path '/'
$ curl localhost:8095/menu
{…,"gstPercent":18,"kitchenTimeoutSeconds":120,…,"cafe":"Udupi Corner (Airport)"}
One JAR, four sources of configuration layered on top of each other: the base file, the prod profile's file (GST 18%, port 8095), an environment variable (CAFE_NAME maps to cafe.name by relaxed binding), and a command-line argument. Later, more specific sources win; the lab measures the order. This is how the same artifact runs on a laptop, in CI and in production with only its environment changed, and why secrets come from the environment or a secret store rather than files in the repository.
When auto-configuration isn't what you want
Every auto-configured bean is conditional, typically @ConditionalOnMissingBean: declare your own bean of that type and Boot's backs off. Run with --debug to print the conditions evaluation report explaining every decision (52 auto-configurations matched and 39 didn't for this small app). For individual settings, use properties (server.port, spring.jackson.*, server.shutdown), which are documented in the reference's "Common Application Properties" appendix and autocompleted by IDEs.
Production features
Boot also packages the operational basics chapter 44 built by hand: graceful shutdown (on by default since Boot 3.4), structured JSON logging (logging.structured.format.console=ecs), and with the Actuator starter, health endpoints for Kubernetes liveness and readiness, metrics via Micrometer, and tracing via OpenTelemetry. The full-depth sections cover them, and the lab measures startup time, memory and shutdown behaviour.
How deep to go in Spring Boot
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Create and run a Boot application; change settings with properties |
| L2 | Use starters, typed configuration properties, profiles and Actuator endpoints |
| L3 | Explain the startup sequence, auto-configuration conditions, configuration precedence, embedded servers, AOT and native options |
| L4 | Diagnose wrong beans, configuration surprises, slow startup, memory use and shutdown problems |
| L5 | Build internal starters and auto-configuration; tune startup and footprint for the platform |
| L6 | Run Boot upgrades and platform standards across many services |
What Boot is
The problem Boot solves
Plain Spring is a container plus libraries. Before Boot (2014), each application assembled them by hand: choose compatible versions of Spring MVC, Jackson, Hibernate, a connection pool and a logging stack, write configuration for each, deploy a WAR into Tomcat, and wire metrics yourself. Spring Boot provides opinionated defaults that you can override:
- Dependency management: curated versions of hundreds of libraries that work together (chapter 43's
spring-boot-dependenciesBOM). - Starters: one dependency per capability, which pulls in a coherent set of libraries.
- Auto-configuration: beans configured automatically based on what's on the class path and in properties, backing off when you define your own.
- Externalised configuration: typed properties from files, environment variables and more, with clear precedence.
- An embedded server and an executable JAR:
java -jar app.jar. - Production features: Actuator health checks, metrics, tracing, info, graceful shutdown, container images.
Spring Boot 4 (November 2025) is built on Spring Framework 7, a Jakarta EE 11 baseline, Java 17+ (25 recommended), Jackson 3 as the default JSON library (Jackson 2 support is deprecated), Hibernate 7.1, Tomcat 11, and a more modular codebase in which auto-configuration is split into technology-specific modules. Upgrades from 3.x are covered by the official migration guide and OpenRewrite recipes.
Startup: what SpringApplication.run does
@SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
In order:
- Create the
Environment: load property sources (command line, environment variables,application.yml, profile files,spring.config.importsources) and activate profiles. - Print the banner. Create the right
ApplicationContexttype (servlet, reactive, or none) based on the class path. - Load bean definitions: your
@Configurationclasses and component scan from the main class's package, plus auto-configuration classes listed inMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsof every JAR on the class path. - Refresh the context (chapter 46): evaluate conditions, instantiate beans, and start the embedded web server.
- Call
ApplicationRunner/CommandLineRunnerbeans, then publishApplicationReadyEventand mark readiness asACCEPTING_TRAFFIC.
Wiring and configuration
Auto-configuration
An auto-configuration is an ordinary @Configuration class guarded by conditions, so it contributes beans only when appropriate:
@AutoConfiguration(after = DataSourceAutoConfiguration.class)
@ConditionalOnClass({ JdbcTemplate.class, DataSource.class }) // only if spring-jdbc is on the class path
@ConditionalOnSingleCandidate(DataSource.class) // only if exactly one DataSource bean exists
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcTemplateAutoConfiguration {
@Bean
@ConditionalOnMissingBean(JdbcOperations.class) // BACK OFF if the app defined its own
JdbcTemplate jdbcTemplate(DataSource dataSource, JdbcProperties props) {
var t = new JdbcTemplate(dataSource);
t.setFetchSize(props.getTemplate().getFetchSize());
return t;
}
}
| Condition | Matches when |
|---|---|
@ConditionalOnClass / OnMissingClass |
A class is (or isn't) on the class path |
@ConditionalOnBean / OnMissingBean / OnSingleCandidate |
Beans of a type exist, don't exist, or there's exactly one |
@ConditionalOnProperty |
A property has a value (havingValue, matchIfMissing) |
@ConditionalOnBooleanProperty |
A boolean property is set (Boot 3.5+) |
@ConditionalOnWebApplication / OnNotWebApplication |
Servlet or reactive web context |
@ConditionalOnResource |
A resource exists |
@ConditionalOnExpression |
A SpEL expression is true |
@ConditionalOnCloudPlatform |
Running on Kubernetes, Cloud Foundry, Heroku, ECS… |
@ConditionalOnThreading |
Virtual threads enabled or not |
The key principle is that auto-configuration backs off. Define your own ObjectMapper, DataSource or SecurityFilterChain bean, and the auto-configured one disappears (through @ConditionalOnMissingBean). The intended way to customise is: properties first, customiser beans second (Jackson2ObjectMapperBuilderCustomizer/JsonMapperBuilderCustomizer, RestClientCustomizer, WebServerFactoryCustomizer, HikariConfig properties), and replacing the bean entirely last.
Debugging auto-configuration:
$ java -jar app.jar --debug # prints the CONDITIONS EVALUATION REPORT at startup
Positive matches:
JdbcTemplateAutoConfiguration matched:
- @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.core.JdbcTemplate'
Negative matches:
MongoAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required class 'com.mongodb.client.MongoClient'
# Actuator equivalent at run time: GET /actuator/conditions
# Exclude an auto-configuration: @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
# or spring.autoconfigure.exclude=…
Writing your own auto-configuration (for an internal platform library) uses the same mechanism: put an @AutoConfiguration class in a JAR, list it in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, and guard everything with conditions. That's how platform teams ship "add this dependency and you get our standard tracing, auth and error format".
Starters
A starter is a dependency-only artifact (essentially a POM) that pulls in everything needed for one capability. The auto-configuration then activates because those classes are now on the class path:
| Starter | Brings |
|---|---|
Web MVC starter (spring-boot-starter-web; Boot 4 adds technology-named starters such as spring-boot-starter-webmvc) |
Spring MVC, embedded Tomcat, Jackson, validation integration |
spring-boot-starter-webflux |
WebFlux, Reactor Netty |
spring-boot-starter-data-jpa |
Spring Data JPA, Hibernate, HikariCP, JDBC |
spring-boot-starter-jdbc |
JdbcClient/JdbcTemplate, HikariCP |
spring-boot-starter-security |
Spring Security with secure defaults |
spring-boot-starter-oauth2-resource-server |
JWT/opaque-token validation |
spring-boot-starter-actuator |
Actuator endpoints, Micrometer |
spring-boot-starter-opentelemetry (Boot 4) |
OpenTelemetry SDK + OTLP export for metrics and traces |
spring-boot-starter-validation |
Hibernate Validator |
spring-boot-starter-test |
JUnit 5/6, AssertJ, Mockito, Spring Test, JSONassert, Awaitility |
spring-boot-starter-kafka, -amqp, -data-redis, -cache… |
Each integration |
Swap the embedded server by excluding the default and adding another (Jetty). Undertow isn't supported on Boot 4's Servlet 6.1 baseline. Starters also exist for third-party integrations (springdoc-openapi-starter-webmvc-ui, resilience4j-spring-boot3) by convention.
Configuration properties
Type-safe binding of a property prefix to a class (preferably an immutable record), with validation and IDE metadata:
# application.yml
shop:
payments:
base-url: https://payments.internal
timeout: 3s # Duration from "3s", "500ms", "PT3S"
max-retries: 2
regions: [eu, us]
api-key: ${PAYMENTS_API_KEY} # from the environment; never commit secrets
upload:
max-size: 10MB # DataSize
@ConfigurationProperties("shop.payments")
@Validated
public record PaymentsProperties(
@NotNull URI baseUrl,
@NotNull @DurationMin(millis = 100) Duration timeout,
@Min(0) @Max(5) int maxRetries,
List<String> regions,
@NotBlank String apiKey) {
public PaymentsProperties {
regions = regions == null ? List.of() : List.copyOf(regions);
}
}
@SpringBootApplication
@ConfigurationPropertiesScan // registers all @ConfigurationProperties classes
class ShopApplication { }
- Relaxed binding:
shop.payments.base-url,shop.payments.baseUrl,SHOP_PAYMENTS_BASEURL(an environment variable) and--shop.payments.base-url=all bind tobaseUrl. Use kebab-case in files. - Conversion:
Duration,DataSize,Period, enums, collections, maps and nested records. - Validation at startup: invalid configuration fails the start with a clear message, which is what you want.
- IDE support:
spring-boot-configuration-processorgenerates metadata for auto-completion and documentation. - Prefer
@ConfigurationPropertiesover scattered@Values: one typed, validated, testable object per concern.
Externalised configuration precedence
Boot assembles property sources in a defined order. Later (higher) sources override earlier ones. Simplified, from lowest to highest:
- Default properties (
SpringApplication.setDefaultProperties) @PropertySourceon configuration classes- Config data files:
application.properties/.ymlpackaged in the JAR, then profile-specificapplication-{profile}.ymlin the JAR, then the same files outside the JAR (./config/, the current directory,spring.config.location/spring.config.additional-location) - OS environment variables
- Java system properties (
-D) SPRING_APPLICATION_JSON- Command-line arguments (
--server.port=9090) - Test properties (
@TestPropertySource,@SpringBootTest(properties=…),@DynamicPropertySource)
# Importing external sources (config trees for Kubernetes-mounted secrets, Vault, config server…)
spring:
config:
import:
- optional:configtree:/etc/secrets/ # each file name = property name, content = value
- optional:file:./local-overrides.yml
application:
name: orders-service
--- # multi-document YAML: profile-specific section
spring:
config:
activate:
on-profile: prod
server:
shutdown: graceful
/actuator/env and /actuator/configprops show the effective values and their sources (secrets are sanitised by default). Lock these endpoints down, as they're sensitive.
Profiles in Boot
Profiles (chapter 46) are activated with spring.profiles.active (property, env var SPRING_PROFILES_ACTIVE, or command line). Boot adds:
- Profile-specific files (
application-prod.yml) andon-profiledocuments. - Profile groups:
spring.profiles.group.prod=postgres,kafka,otel. spring.profiles.default(used when no profile is active).- Tests:
@ActiveProfiles("test").
Keep the number of profiles small, and keep production-specific values in the deployment environment (environment variables, mounted config), not in a prod profile file inside the JAR. Then the artifact stays environment-neutral.
Running in production
Embedded servers
Boot runs the web server inside the application process: Tomcat by default for MVC, Jetty as an option, and Reactor Netty for WebFlux. Configure it with properties:
server:
port: 8080
shutdown: graceful # (the default since Boot 3.4)
http2.enabled: true
compression.enabled: true
forward-headers-strategy: framework # trust X-Forwarded-* from the proxy (chapter 31 of Vol. 2)
tomcat:
threads.max: 200 # platform-thread pool (irrelevant to request handling with virtual threads)
max-connections: 8192
accept-count: 100
connection-timeout: 10s
max-swallow-size: 2MB
spring:
threads.virtual.enabled: true # Tomcat request handling, @Async and scheduling on virtual threads
servlet.multipart.max-file-size: 10MB
TLS can be configured with SSL bundles (spring.ssl.bundle.*, with reloading of rotated certificates), though in most deployments TLS terminates at the ingress or load balancer. Fine-tune with a WebServerFactoryCustomizer<TomcatServletWebServerFactory> bean.
Actuator
Actuator adds production endpoints under /actuator. Only health is exposed over HTTP by default, and you opt in to others:
| Endpoint | Shows |
|---|---|
/health (+ /health/liveness, /health/readiness) |
Application health, aggregated from health indicators (DB, disk, Redis, Kafka…) |
/info |
Build info, git commit, Java and OS info (configurable) |
/metrics, /prometheus |
Micrometer metrics (the latter in Prometheus format) |
/env, /configprops |
Effective configuration (sanitised) |
/beans, /conditions, /mappings |
Beans, auto-config decisions, request mappings |
/loggers |
View and change log levels at run time |
/threaddump, /heapdump |
Diagnostics (sensitive: a heap dump contains secrets and PII) |
/scheduledtasks, /caches, /flyway, /liquibase, /sbom |
Specific features |
/shutdown |
Graceful shutdown (disabled by default) |
management:
server.port: 8081 # actuator on a separate port, not exposed through the public ingress
endpoints.web.exposure.include: health,info,prometheus
endpoint:
health:
probes.enabled: true # /health/liveness and /health/readiness (auto-enabled on Kubernetes)
show-details: when-authorized
group.readiness.include: readinessState,db,redis # what must be healthy to receive traffic
info.git.mode: full
observations.key-values.application: orders-service
Security: Actuator endpoints can leak configuration, heap contents and environment variables, or change log levels. Expose only what's needed, put them on a separate management port or network, and require authentication for anything beyond health and info. Exposed /heapdump and /env endpoints are a recurring cause of real breaches.
Health, liveness and readiness
Kubernetes distinguishes (Part VI):
- Liveness: "is this process broken beyond recovery?" If it fails, restart the container. It should reflect only internal state (a deadlock, a corrupted state), and never external dependencies. If the database is down and liveness checks the database, Kubernetes restarts every pod, which doesn't help and causes a restart storm.
- Readiness: "can this instance serve traffic right now?" If it fails, it's removed from load balancing but not restarted. It's appropriate during startup warmup, during shutdown, or when a required dependency is unavailable (choose deliberately: if every replica fails readiness together, you have a total outage instead of degraded service).
- Startup probes: give slow-starting apps time before liveness checks begin.
Boot exposes these as availability states (LivenessState.CORRECT/BROKEN, ReadinessState.ACCEPTING_TRAFFIC/REFUSING_TRAFFIC), driven by the application lifecycle: readiness becomes ACCEPTING_TRAFFIC after runners complete, and REFUSING_TRAFFIC when shutdown begins. You can change them yourself with AvailabilityChangeEvent.publish(...).
// A custom health indicator (included in /health and optionally in readiness groups)
@Component
class PaymentsHealth implements HealthIndicator {
private final PaymentClient client;
PaymentsHealth(PaymentClient client) { this.client = client; }
@Override public Health health() {
try {
var latency = client.ping(Duration.ofMillis(500));
return Health.up().withDetail("latencyMs", latency.toMillis()).build();
} catch (Exception e) {
return Health.down(e).build();
}
}
}
# Kubernetes probes
livenessProbe: { httpGet: { path: /actuator/health/liveness, port: 8081 }, periodSeconds: 10, failureThreshold: 3 }
readinessProbe: { httpGet: { path: /actuator/health/readiness, port: 8081 }, periodSeconds: 5, failureThreshold: 2 }
startupProbe: { httpGet: { path: /actuator/health/liveness, port: 8081 }, periodSeconds: 5, failureThreshold: 30 }
Health checks must be cheap and time-bounded. Cache expensive checks, and don't let a slow dependency check hang the probe.
Metrics, tracing and observability
Boot's observability is built on Micrometer, a vendor-neutral instrumentation facade (the SLF4J of metrics):
- Metrics:
MeterRegistrywith counters, gauges, timers, distribution summaries and long task timers, exported to Prometheus, OTLP, Datadog, CloudWatch and others. Boot auto-instruments HTTP server and client requests (http.server.requestswith method, URI template, status and outcome), JVM (memory, GC, threads, classes), the Hikari pool, caches, Kafka, executors, Tomcat, logback events and more. - The Observation API (Micrometer 1.10+): instrument once, and get metrics and trace spans from the same observation.
- Tracing: Micrometer Tracing bridges to OpenTelemetry (or Brave), propagating W3C
traceparentthroughRestClient,WebClient, Kafka and so on, and puttingtraceId/spanIdinto the logging MDC. Boot 4 adds a dedicated OpenTelemetry starter with OTLP export.
@Service
class CheckoutService {
private final Counter ordersPlaced;
private final ObservationRegistry observations;
CheckoutService(MeterRegistry registry, ObservationRegistry observations) {
this.ordersPlaced = Counter.builder("shop.orders.placed").description("orders placed").register(registry);
this.observations = observations;
}
Order checkout(Cart cart) {
return Observation.createNotStarted("shop.checkout", observations)
.lowCardinalityKeyValue("channel", cart.channel()) // low cardinality: OK as a metric tag
.highCardinalityKeyValue("cart.id", cart.id()) // high cardinality: span attribute only
.observe(() -> {
var order = doCheckout(cart);
ordersPlaced.increment();
return order;
});
}
}
// Or declaratively: @Observed(name = "shop.checkout") on the method (an AOP proxy; mind self-invocation)
management:
tracing.sampling.probability: 0.1 # 10% of traces
otlp.tracing.endpoint: http://otel-collector:4318/v1/traces
metrics.distribution.percentiles-histogram.http.server.requests: true # enables p99 via histograms
Cardinality discipline: metric tags must have a bounded set of values (HTTP method, route template, status class). Putting user IDs, order IDs or raw URLs into metric tags explodes the time-series count and can take down your metrics backend. Those belong in traces and logs. Vol. 6 covers observability in depth.
Graceful shutdown
When Kubernetes terminates a pod, it sends SIGTERM, removes the pod from endpoints (asynchronously, which takes a few seconds to propagate to every load balancer), and after terminationGracePeriodSeconds sends SIGKILL. A graceful shutdown:
- Stops accepting new requests (readiness →
REFUSING_TRAFFIC). - Lets in-flight requests finish, up to a timeout.
- Stops consumers and schedulers (
SmartLifecycle.stop, ordered by phase). - Closes resources: connection pools, producers (flushing buffered messages), caches.
- Exits.
server.shutdown: graceful # default since Boot 3.4
spring.lifecycle.timeout-per-shutdown-phase: 30s
# Kubernetes: avoid dropping requests while endpoint removal propagates
lifecycle:
preStop:
exec: { command: ["sh", "-c", "sleep 10"] } # keep serving briefly while load balancers update
terminationGracePeriodSeconds: 45 # > preStop + shutdown phase timeout
The same pattern appears in every stack: Go's http.Server.Shutdown(ctx) after signal.NotifyContext, ASP.NET Core's IHostApplicationLifetime with HostOptions.ShutdownTimeout, Axum's with_graceful_shutdown(signal), Node's server.close(), and Phoenix/BEAM application stop with supervision-tree shutdown order.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
go func() { _ = srv.ListenAndServe() }()
<-ctx.Done() // SIGTERM received
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx) // stop accepting; wait for in-flight requests
Testing and startup
Test slices
Boot's testing support starts only the parts of the context a test needs, which is faster and more focused than the full application:
| Annotation | Loads | For |
|---|---|---|
@SpringBootTest |
The full application context (optionally a real server: webEnvironment = RANDOM_PORT) |
End-to-end and integration tests |
@WebMvcTest(OrderController.class) |
MVC infrastructure + that controller, @ControllerAdvice, converters, security filters. No services or repositories (mock them) |
Controller tests with MockMvc/MockMvcTester |
@WebFluxTest |
WebFlux equivalent | WebTestClient |
@DataJpaTest |
JPA, repositories, EntityManager, an embedded DB by default (use Testcontainers for the real database), transactional with rollback |
Repository and query tests |
@JdbcTest, @DataJdbcTest, @DataMongoTest, @DataRedisTest |
The respective data layer | Persistence tests |
@JsonTest |
Jackson configuration, JacksonTester |
Serialisation tests |
@RestClientTest |
RestClient/RestTemplate + MockRestServiceServer |
HTTP client tests |
@GraphQlTest, @WebServiceClientTest |
… | … |
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvcTester mvc; // AssertJ-based MockMvc (Boot 3.4+)
@MockitoBean OrderService service; // replaces the bean with a Mockito mock (replaced @MockBean)
@Test void returns404ForMissingOrder() {
given(service.find("nope")).willThrow(new OrderNotFound("nope"));
assertThat(mvc.get().uri("/orders/nope"))
.hasStatus(HttpStatus.NOT_FOUND)
.bodyJson().extractingPath("$.title").isEqualTo("Order not found");
}
}
Testcontainers integration (@ServiceConnection), context caching, and the overall test strategy are covered in chapter 54. Boot 4 adds RestTestClient for testing MVC applications either through MockMvc or against a running server.
AOT processing, native images and startup
Spring's flexibility (classpath scanning, reflection, conditions evaluated at startup, runtime proxies) costs startup time and memory. Boot's answers:
1. Spring AOT (ahead-of-time processing): at build time, Spring starts the application context in a special mode, evaluates the bean definitions and conditions for a fixed environment, and generates Java source code that registers exactly those beans programmatically. It also generates reachability metadata (reflection, resources, proxies, serialisation hints) for GraalVM. At run time there's no scanning and no condition evaluation.
$ ./mvnw -Pnative spring-boot:build-image # Buildpacks + GraalVM native image (needs the native profile / plugin)
$ ./mvnw -Pnative native:compile # local GraalVM native executable
$ ./gradlew nativeCompile
# Custom hints for reflection your code needs:
# @RegisterReflectionForBinding(OrderDto.class) or implement RuntimeHintsRegistrar
Closed-world constraints: profiles and @Conditional beans are fixed at build time (you can't change which beans exist with a run-time property), and dynamic class loading or reflection without hints fails at run time. Test the native build in CI (nativeTest).
2. GraalVM native image: startup in tens of milliseconds, memory use of tens of MB, and instant peak performance (no warmup), but generally lower peak throughput than the C2 JIT without PGO, build times of minutes, and the closed-world limits above. Best for serverless, CLIs, scale-to-zero and high-density deployments.
3. CDS and the JDK AOT cache (Project Leyden): keep the regular JVM (full JIT and dynamism) but archive class loading and linking, and with newer JDKs profiles too, from a training run. Spring Boot supports creating the archive by extracting the JAR and running a training run that exits after the context starts. Typical gains are 30–50% faster startup with no closed-world restrictions.
$ java -Djarmode=tools -jar app.jar extract --destination app
$ java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar app/app.jar # training run (JDK 25+)
$ java -XX:AOTCache=app.aot -jar app/app.jar # fast start
# On older JDKs: -XX:ArchiveClassesAtExit=app.jsa then -XX:SharedArchiveFile=app.jsa (CDS)
4. Lazy initialisation (spring.main.lazy-initialization=true): beans are created on first use. Startup is faster, but errors surface later and the first requests are slower, so use it with care in production.
Container images
$ ./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=registry/shop/orders:1.5.0
$ ./gradlew bootBuildImage --imageName=registry/shop/orders:1.5.0
Cloud Native Buildpacks (Paketo) produce OCI images without a Dockerfile: a tuned JRE, layered JARs for caching (chapter 42), a memory calculator that sets JVM flags from the container's limit, a non-root user, CDS or AOT-cache support, and SBOMs. Alternatives: Jib (Maven/Gradle plugin, daemonless, layered) or a hand-written multi-stage Dockerfile for full control. Whatever you choose: pin the base image, run as non-root, set -XX:MaxRAMPercentage, include a health endpoint, and scan the image.
Alternatives
Boot's peers in other ecosystems
| Framework | Language | Philosophy | Startup and DI | Notes |
|---|---|---|---|---|
| Spring Boot | Java/Kotlin | Convention + auto-config over the huge Spring ecosystem | Runtime DI (AOT optional); JVM or native | The broadest integrations; the enterprise default |
| Quarkus | Java/Kotlin | "Supersonic subatomic Java": build-time processing of everything possible (CDI via ArC, Hibernate, REST) | Build-time DI; fast JVM startup; first-class native | Dev mode with live reload and Dev Services (auto-started Testcontainers) |
| Micronaut | Java/Kotlin/Groovy | Compile-time DI and AOP via annotation processors | No reflection; fast startup; native-friendly | Small memory footprint |
| Helidon | Java | Helidon SE (functional, minimal) / MP (MicroProfile); its Níma web server was designed for virtual threads | — | Oracle |
| ASP.NET Core | C# | A generic host (WebApplication.CreateBuilder): DI, config, logging and hosting in one model; minimal APIs or controllers |
Runtime DI; Native AOT for minimal APIs | Very fast (Kestrel); built-in health checks, OpenTelemetry, rate limiting, output caching |
| NestJS | TypeScript | Angular-inspired modules, DI and decorators on Express or Fastify | Runtime DI | The most "Spring-like" Node framework |
| Phoenix | Elixir | Router + plugs + contexts on the BEAM; LiveView for real-time UI | Starts a supervision tree; releases bundle the runtime | Telemetry built in; hot code upgrades possible |
| FastAPI / Django | Python | FastAPI: type-hint-driven async APIs. Django: batteries-included (ORM, admin, auth) | Import-time wiring | Django is the closest to Boot's "everything included" in Python |
Go (net/http + libraries) |
Go | No framework is the norm: the standard library plus small packages (chi, pgx, sqlc, slog, OTel), wired in main |
Instant startup, no DI container | Health, metrics and graceful shutdown are written explicitly (a few dozen lines) |
| Rust (Axum/Actix + crates) | Rust | Assemble from crates: Tokio, Axum, tower-http, sqlx, tracing, config | Instant startup | Loco.rs offers a Rails-like, batteries-included experience |
The underlying trade-off is integrated convention (Spring Boot, Django, Rails, Phoenix, ASP.NET) versus explicit assembly (Go, Rust). Convention gives speed and consistency across teams, and much behaviour is implicit, so you must learn the framework's rules (auto-configuration, proxies). Explicit assembly gives full visibility and minimal magic, at the cost of more code and more decisions per service.
Lab: what Boot decides, and what it costs
Spring Boot 4.1.1 on JDK 21 (and a JDK 25 runtime for the AOT cache), using the CafeApplication from Start here. Times are wall-clock from process start to the first successful HTTP response, on a 2-core machine.
Experiment 1: configuration precedence, measured
The same property, cafe.name, set in up to four places at once:
all four set (file, env CAFE_NAME, -Dcafe.name, --cafe.name): "cafe":"from-command-line"
no command-line argument: "cafe":"from-system-property"
environment variable and file only: "cafe":"from-env"
file only: "cafe":"Udupi Corner"
The order, from strongest: command-line arguments, Java system properties, OS environment variables, profile-specific files, application.properties (the full list has about fifteen sources, including test properties, SPRING_APPLICATION_JSON and config trees for Kubernetes secrets). When a value in production isn't what the file says, something higher in this list is setting it. And a bad value fails at startup, with its origin:
APPLICATION FAILED TO START
Failed to bind properties under 'cafe.gst-percent' to int:
Property: cafe.gst-percent
Value: "five"
Origin: "cafe.gst-percent" from property source "commandLineArgs"
Reason: failed to convert java.lang.String to int
That's the benefit of typed @ConfigurationProperties over reading strings where they're used: a misconfigured deploy never becomes ready (so the old version keeps serving), instead of failing on the first order. Add @Validated with Bean Validation constraints to check ranges too.
Experiment 2: auto-configuration backing off
--debug prints the conditions evaluation report: 52 auto-configurations matched for this app and 39 didn't (no XML, CBOR, Gson, JMX…). With an extra profile that defines its own JsonMapper bean configured for snake_case:
JacksonAutoConfiguration#jacksonJsonMapper:
Did not match:
- @ConditionalOnMissingBean (types: tools.jackson.databind.json.JsonMapper; SearchStrategy: all)
found beans of type 'tools.jackson.databind.json.JsonMapper' myJsonMapper (OnBeanCondition)
"dishes":[{"id":1,"name":"Masala dosa","price_paise":9000},{"id":2,"name":"Filter coffee","price_paise":3000}]
Boot's mapper wasn't created, and the HTTP layer used ours. This is the escape hatch, and also a trap: replacing the mapper also discards everything Boot configured on its own mapper (modules, spring.jackson.* properties, customisers). Prefer a JsonMapperBuilderCustomizer bean, which adjusts Boot's mapper instead of replacing it; the same pattern exists for most auto-configured infrastructure.
Experiment 3: startup time and memory
JDK HttpServer menu API (chapter 32 Start Here), JDK 21: 244 ms, RSS 49 MB
Spring Boot, JDK 21: 3137 ms, RSS 162 MB
Spring Boot, JDK 21, spring.main.lazy-initialization: 2754 ms
Spring Boot, JDK 25: 3080 ms
Spring Boot, JDK 25 with AOT cache: 1451 ms, RSS 150 MB
Boot's convenience costs about 3 seconds and 110 MB here, mostly loading and linking the 7,500 classes (measured with -Xlog:class+load) of the JDK, Spring, Tomcat and Jackson and evaluating auto-configuration. For a long-running service that's irrelevant; for scaling out under a traffic spike, or for jobs and functions that start often, it matters. Lazy initialisation helped little because the web layer must start anyway. The JDK's AOT cache (chapter 39) halved startup with no code change: one training run (-XX:AOTCacheOutput=cafe.aot -Dspring.context.exit=onRefresh, which stops the app right after the context starts) produced a 57 MB cache of loaded and linked classes, and later runs started from it. The cache needs a classpath of JARs, not directories, and the same JDK. Going further, Spring AOT plus GraalVM native-image compiles the whole application ahead of time, typically starting in well under 100 ms with much less memory, at the cost of long builds and closed-world restrictions on reflection (full-depth section).
Experiment 4: graceful shutdown
A /report endpoint takes 3 seconds; SIGTERM arrives half a second into a request:
server.shutdown=graceful: process exited 2570 ms after SIGTERM | client: report ready [HTTP 200]
GracefulShutdown : Commencing graceful shutdown. Waiting for active requests to complete
GracefulShutdown : Graceful shutdown complete
server.shutdown=immediate: process exited 66 ms after SIGTERM | client: [HTTP 000] exit 52 (empty reply)
Graceful mode stopped accepting connections, let the in-flight request finish and then exited; immediate mode killed it. spring.lifecycle.timeout-per-shutdown-phase (default 30 s) caps the wait, and it must be shorter than the platform's kill timeout. In Kubernetes, pair it with a readiness probe that fails during shutdown (Actuator's readiness state does this) and, often, a short preStop sleep so the load balancer stops routing before the server stops accepting.
Try it yourself
- Add
logging.structured.format.console=ecsand compare one request's log line with chapter 44's hand-written JSON logs. - Remove the Jackson JARs from the classpath and run with
--debug. Which auto-configurations change, and what does/menureturn now? - Write a tiny auto-configuration of your own (
@AutoConfigurationregistered inMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports) that provides aClockbean unless the application defines one. - Measure experiment 3 for a Quarkus or Micronaut equivalent (both do dependency injection at build time) and for a Go
net/httpserver.
Revision sheet: Spring Boot
Key ideas
- Boot 4 (November 2025; 4.1 in 2026): Spring Framework 7, Jakarta EE 11, Java 17+ (25 recommended), Jackson 3 default, Hibernate 7.1, Tomcat 11, modular auto-configuration and technology-named starters.
- Startup:
SpringApplication.run→ environment prepared → context created → bean definitions loaded (including auto-configuration viaAutoConfiguration.imports) → refresh → web server started → runners → ready events. - Auto-configuration:
@AutoConfigurationclasses with@ConditionalOnClass,@ConditionalOnMissingBean,@ConditionalOnProperty, ordering; customisers rather than replacements; conditions report. - Configuration: property sources and precedence; profiles and profile groups; relaxed binding;
@ConfigurationPropertiesrecords with validation; config trees for Kubernetes secrets;spring.config.import. - Production: embedded Tomcat/Jetty; Actuator (health with liveness/readiness groups, info, metrics, prometheus, loggers, conditions); Micrometer metrics, tracing and OpenTelemetry starter; structured logging; graceful shutdown default.
- Testing:
@SpringBootTest, slices (@WebMvcTest,@DataJpaTest,@JsonTest), Testcontainers@ServiceConnection,RestTestClient. - Startup and images: Spring AOT, GraalVM native images, JVM AOT cache (Leyden), CDS, layered JARs and Buildpacks images.
- Peers: Quarkus, Micronaut, Helidon, ASP.NET Core, NestJS, Django, Rails, Phoenix.
Numbers to remember
- Lab: Boot app started in about 3.1 s with 160 MB RSS vs 0.24 s and 49 MB for a JDK
HttpServer; the JDK 25 AOT cache cut startup to 1.45 s; graceful shutdown completed a 3 s request, immediate shutdown dropped it. - Graceful shutdown phase timeout default 30 s.
Pitfalls
- Replacing auto-configured beans instead of customising them (losing Boot's settings).
- Mystery values from higher-precedence sources (env vars, system properties).
- Reading configuration as raw strings at use sites; secrets in
application.propertiesin git. - Exposing all Actuator endpoints publicly.
- Heavy
@SpringBootTestfor everything instead of slices and plain unit tests. - Shutdown timeouts longer than the platform's kill timeout.
Glossary
- Starter: a curated dependency for one capability.
- Auto-configuration: conditional configuration contributed by Boot or libraries.
- Relaxed binding: mapping
CAFE_NAME,cafe.nameandcafe-nameto the same property. - Actuator: Boot's operational endpoints.
- Spring AOT: build-time processing of bean definitions into generated code.
- Layered JAR: a JAR organised so container image layers change rarely.