Production-ready Spring Boot
Spring Boot was designed for production from the start: health checks, metrics, externalised configuration, graceful shutdown and container images are built in. This lesson covers what to switch on before real users arrive, and ends with the track's capstone project.
Actuator: health and metrics
spring-boot-starter-actuator adds operational endpoints under /actuator. Expose only what you need:
management.endpoints.web.exposure.include=health,info,prometheus
management.endpoint.health.show-details=when-authorized
management.endpoint.health.probes.enabled=truecurl localhost:8080/actuator/healthWith details shown (show-details=always, fine on a laptop), the response lists each check:
{"components":{"db":{"details":{"database":"H2","validationQuery":"isValid()"},"status":"UP"},"diskSpace":{"details":{…},"status":"UP"},"livenessState":{"status":"UP"},"ping":{"status":"UP"},"readinessState":{"status":"UP"},"ssl":{"details":{"expiringChains":[],"invalidChains":[],"validChains":[]},"status":"UP"}},"groups":["liveness","readiness"],"status":"UP"}- Health aggregates checks for the database, disk, message brokers and more; add your own by implementing
HealthIndicator. - Liveness (
/actuator/health/liveness: "restart me if this fails") and readiness (/actuator/health/readiness: "don't send me traffic yet") map directly to Kubernetes probes. - Metrics via Micrometer: request counts and latencies per endpoint, JVM memory and GC, connection pool usage, and your own (
meterRegistry.counter("orders.placed").increment()). Addmicrometer-registry-prometheusto expose them at/actuator/prometheusfor Prometheus and Grafana.
Never expose sensitive endpoints (env, heapdump, loggers) publicly. Put the management port on an internal network (management.server.port=9090) or secure it with Spring Security.
Configuration and secrets
The same JAR runs in every environment, configured from outside:
java -jar shop.jar --spring.profiles.active=prod
SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/shop SPRING_DATASOURCE_PASSWORD=… java -jar shop.jar- Keep secrets out of
application.propertiesin Git; inject them as environment variables, Kubernetes Secrets, or from a vault (Spring Cloud Vault, AWS Secrets Manager integrations). - Validate your
@ConfigurationPropertiesrecords with@Validatedand constraints, so a missing setting stops the app at startup with a clear message. - Use profiles sparingly (
dev,test,prod); prefer environment variables for values that differ.
Logging
Spring Boot logs to the console by default, which is exactly right for containers. For log platforms, switch to structured JSON logs with one property:
logging.structured.format.console=ecs # or logstash, gelfEach line becomes a JSON object with the level, logger, message and trace IDs, ready for Elasticsearch, Loki or CloudWatch. Change log levels per package (logging.level.com.example.shop=debug) without code changes.
Graceful shutdown and virtual threads
server.shutdown=graceful # finish in-flight requests on SIGTERM (the default since Boot 3.4)
spring.lifecycle.timeout-per-shutdown-phase=20s
spring.threads.virtual.enabled=true # handle requests on virtual threads (Java 21+)With virtual threads (see the Java track's concurrency lesson), each request runs on a lightweight thread, so blocking calls to databases and other services no longer limit throughput the way a fixed thread pool does. One property turns them on for Tomcat, @Async methods and scheduled tasks.
Building container images
Spring Boot can build an optimised OCI image without a Dockerfile, using Cloud Native Buildpacks:
./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=myshop/shop:1.4.0
docker run -p 8080:8080 -e SPRING_PROFILES_ACTIVE=prod myshop/shop:1.4.0Or write a Dockerfile that uses Boot's layered JAR, so dependencies (which rarely change) and your code (which changes often) are separate cacheable layers:
FROM eclipse-temurin:25-jre AS extract
WORKDIR /app
COPY target/shop.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --launcher --destination extracted
FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=extract /app/extracted/dependencies/ ./
COPY --from=extract /app/extracted/spring-boot-loader/ ./
COPY --from=extract /app/extracted/snapshot-dependencies/ ./
COPY --from=extract /app/extracted/application/ ./
USER 1000
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]Faster startup
| Technique | Effect |
|---|---|
| Class Data Sharing / AOT cache (Java 24+) | Noticeably faster JVM startup, still a normal JVM |
| Spring AOT | Pre-computes bean definitions at build time |
GraalVM native image (./mvnw -Pnative native:compile) |
Starts in tens of milliseconds with a small memory footprint; longer builds and some reflection limits |
Native images suit serverless functions and command-line tools; for long-running services the regular JVM's peak performance is usually better.
Production checklist
- Actuator health with liveness/readiness probes; metrics scraped by Prometheus; dashboards and alerts.
- Flyway migrations and
ddl-auto=validate;open-in-view=false; connection pool sized for your database. - Spring Security configured deny-by-default; HTTPS at the load balancer; secrets from the environment.
- Problem Details for errors; no stack traces in responses.
- Structured logs with trace IDs; OpenTelemetry tracing across services.
- Graceful shutdown; several instances behind a load balancer; stateless (sessions in Redis or tokens).
- Dependency updates automated (Dependabot/Renovate); stay on supported Spring Boot and Java versions.
- A CI pipeline that runs tests (with Testcontainers), builds the image and deploys.
🎓 Spring Boot track complete!
You've learned how Spring Boot projects work, REST controllers, beans and dependency injection, Spring Data JPA, validation and Problem Details, testing with slices and MockMvcTester, Spring Security, relationships, paging and Flyway migrations, microservices patterns, and running Spring Boot in production.
Capstone project: a library service
- Domain:
Book,Member,Loanentities with Flyway migrations, on PostgreSQL (Testcontainers in tests). - API: paged and sorted book search, borrowing and returning books, a member's loans; records as DTOs; Problem Details errors, including
409when no copy is available. - Rules: at most 5 loans per member; borrowing runs in a transaction that locks the book's row (
@Lock(PESSIMISTIC_WRITE)), so the last copy can't be lent twice. - Security: members see only their own loans; librarians manage books (
@PreAuthorize); JWT resource server or HTTP Basic for the exercise. - Async: publish a
LoanOverdueevent daily with@Scheduled, consumed by a notification component. - Tests:
@WebMvcTestfor controllers,@DataJpaTestfor queries, one@SpringBootTestfor the borrow flow, and security tests for forbidden access. - Production: Actuator probes, structured logs, virtual threads, a buildpack image, and a GitHub Actions pipeline.
1.What is the readiness probe for?
2.How do you configure the same JAR differently in production?
3.What does spring.threads.virtual.enabled=true do?