Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·47

Spring Boot

Exercises for Volume 3, chapter 47: the problem Boot solves and what SpringApplication.run does; auto-configuration and starters; configuration properties, externalised configuration precedence and profiles; embedded servers; Actuator, health, liveness and readiness; metrics, tracing and observability; graceful shutdown; test slices; AOT processing, native images and startup; container images; and Boot's peers in other ecosystems. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as before. The code is Spring Boot 4.1.1 on JDK 21 (Spring Framework 7, Jackson 3, Tomcat 11), run from local JARs because Maven Central is blocked in this environment. Actuator and Bean Validation weren't among the available JARs, so those exercises give expected outputs. Every quoted output below is real.

Five of the outputs catch experienced developers:

  • P1. A typo'd property, --tiffinbox.paymnts.timeout=9s, was silently ignored, and the timeout stayed 750 ms (from TIFFINBOX_PAYMENTS_TIMEOUT=750ms). The same run bound the environment variables …_CITIES_0_=HYD and …_CITIES_1_=BLR into the list [HYD, BLR], and 2MB into 2,097,152 bytes.
  • P2. Boot 4's JSON accepted an unknown field and truncated qty: 2.9 to 2, with no error.
  • P3. The default error body for a thrown IllegalStateException("db password is hunter2") didn't leak the message. With spring.mvc.problemdetails.enabled=true, the 404 became application/problem+json, but the 500 kept the old format.
  • P4. With spring.threads.virtual.enabled=true, the handler ran on VirtualThread[#33,tomcat-handler-2] instead of http-nio-18047-exec-2.
  • P5. A custom auto-configuration with @ConditionalOnMissingBean and @ConditionalOnProperty(matchIfMissing = true) created its default bean. It backed off when a user bean existed or when tiffinbox.sms.enabled=false. The --debug report explained each decision.

The chapter's lab already covered these, and the exercises build on them rather than repeat them:

  • configuration precedence across four sources;
  • a binding failure report for gst-percent=five;
  • Jackson auto-configuration backing off for a user JsonMapper;
  • startup of 3,137 ms on JDK 21, against 1,451 ms with JDK 25 and an AOT cache, and 244 ms for the plain JDK server;
  • graceful shutdown (2,570 ms with a 200 response) against immediate shutdown (66 ms with an empty reply).

Coverage map.

Chapter component Exercises
what Boot solves; SpringApplication.run T1, P9
auto-configuration; conditions; starters T2, P5
configuration properties; binding; relaxed names T3, P1
precedence; profiles T3, P1
embedded servers; virtual threads T4, P4
JSON defaults and error handling T5, P2, P3
Actuator; health, liveness, readiness T6, P6
metrics, tracing, observability T7, P6
graceful shutdown T4, P8
test slices T8, P7
AOT, native images, startup; container images T9, P9
Boot's peers T9

Theory

T1. What Boot is and what run does

  1. Boot sits on top of Spring Framework (ch46) and adds: - dependency management (the BOM: ch43); - starters; - auto-configuration; - externalised configuration; - an embedded server; - production features (Actuator, metrics, health); - packaging (layered JARs, images: ch42).

Which of these are "just Spring", configured for you, and which are new? 2. Trace SpringApplication.run: 1. bootstrap context and listeners; 2. prepare the Environment (property sources, profiles); 3. print the banner; 4. create the right ApplicationContext (servlet, reactive or none); 5. load auto-configurations from AutoConfiguration.imports; 6. refresh: bean definitions, conditions, singletons, the embedded server starting via SmartLifecycle; 7. runners (ApplicationRunner, CommandLineRunner); 8. ApplicationReadyEvent.

Where does P1's "Started App in 2.544 seconds (process running for 2.926)" come from, and what's the gap between the two numbers? 3. Boot's opinions are defaults you can change. When should a team override a default (JSON strictness: P2; error format: P3; virtual threads: P4), and how do you keep overrides discoverable (one configuration module, documented properties)?

T2. Auto-configuration and starters

  1. Explain conditions: - @ConditionalOnClass (a library on the class path); - @ConditionalOnMissingBean (back off if the user defined one); - @ConditionalOnProperty (feature switches); - @ConditionalOnBean; - @ConditionalOnWebApplication; - @ConditionalOnResource.

P5's report showed SmsAutoConfiguration#defaultSms matched with the reasons, and the bean disappeared with tiffinbox.sms.enabled=false and was replaced by a user bean. How do you read --debug (positive matches, negative matches, exclusions, unconditional classes)? 2. Ordering: @AutoConfiguration(before=…, after=…), why @ConditionalOnMissingBean is evaluated against beans registered so far (user configuration first, then auto-configurations), and the classic bug where a user @Bean in an auto-configuration-like class is registered too late. 3. Starters: what a starter contains (dependencies only, no code) against an auto-configure module (the code). Design a tiffinbox-observability-spring-boot-starter (ch42's S3) that provides logging, metrics and HTTP client defaults, can be switched off by properties, and backs off for user beans.

T3. Configuration properties, precedence and profiles

  1. P1 bound these into @ConfigurationProperties("tiffinbox.payments") record PaymentsProps(Duration timeout, DataSize maxBody, List<String> cities, Map<String, Integer> gstByCity): - TIFFINBOX_PAYMENTS_TIMEOUT=750ms → 750 ms; - TIFFINBOX_PAYMENTS_MAXBODY=2MB → 2,097,152 bytes; - …_CITIES_0_=HYD and …_CITIES_1_=BLR → [HYD, BLR]; - --tiffinbox.payments.gst-by-city.HYD=5 → {HYD=5}.

Explain relaxed binding (kebab-case canonical, environment-variable mapping, indexed lists), conversion (Duration, DataSize, enums), and immutable record binding. 2. The silent typo: --tiffinbox.paymnts.timeout=9s was ignored. Why doesn't Boot fail on unknown properties, and how do you catch typos? - configuration metadata plus IDE warnings; - @Validated with @NotNull on required fields; - a startup check comparing set keys against known prefixes; - spring-boot-properties-migrator for renamed keys. 3. The lab's precedence: command line > system property > environment > file. Explain the full order (about 15 sources: test properties, SPRING_APPLICATION_JSON, config trees, profile-specific files outside and inside the JAR, spring.config.import), profile groups, and spring.config.activate.on-profile. Design TiffinBox's configuration layout for local, staging and production.

T4. Embedded servers, threads and graceful shutdown

  1. The embedded server: Tomcat (the default for MVC), Jetty, Undertow (dropped in Boot 4), Netty (WebFlux). What does "embedded" change compared with deploying a WAR (ch42's T1)? Which settings matter: - threads; - max-connections; - accept-count; - connection and keep-alive timeouts; - header and body limits (ch44's T6); - compression (ch45); - HTTP/2; - forwarded headers?
  2. Virtual threads. P4 moved request handling from http-nio-18047-exec-2 to VirtualThread[#33,tomcat-handler-2] with one property. What else does spring.threads.virtual.enabled=true switch (the @Async executor, schedulers, some messaging listeners)? What must you still bound (the database pool, downstream bulkheads: ch38's P6)? And what about pinning on JDK 21 (ch38's lab)?
  3. Graceful shutdown. The lab: graceful exited 2,570 ms after SIGTERM with the client getting 200, while immediate exited in 66 ms with an empty reply. Configure: - server.shutdown=graceful (the default since 3.4); - spring.lifecycle.timeout-per-shutdown-phase; - readiness changes on shutdown; - Kubernetes preStop and terminationGracePeriodSeconds.

What happens to @Scheduled tasks and message listeners during shutdown?

T5. JSON and error-handling defaults

  1. P2: Boot 4's Jackson 3 configuration accepted {"dish":"idli","qty":2.9,"coupon":"FREE"} and returned {"dish":"idli","qty":2}, ignoring the unknown field and truncating the float. Contrast this with ch44's P3 (plain Jackson 2 rejected unknown fields). Configure TiffinBox's API with: - spring.jackson.deserialization.fail-on-unknown-properties; - coercion configuration through a JsonMapperBuilderCustomizer; - strict duplicate detection; - StreamReadConstraints.

P3 showed timestamps as ISO strings ("placedAt":"2026-11-14T07:00:00Z", "deliveryDate":"2026-11-14"). Note that Jackson 3 changed several defaults. 2. Error handling. P3's default error body was {"timestamp":…,"status":500,"error":"Internal Server Error","path":"/boom"}, which didn't leak the message containing a password. With spring.mvc.problemdetails.enabled=true, the 404 became application/problem+json ({"detail":"No static resource nope.","instance":"/nope","status":404,"title":"Not Found"}) while the 500 from an unhandled exception kept the old format. Why? Build a @RestControllerAdvice extending ResponseEntityExceptionHandler that maps the domain errors and the fallback 500 to RFC 9457 with codes and traceId (ch44's T9). 3. Which server.error.* properties leak information (include-message, include-stacktrace, include-binding-errors, include-exception)? Add a test asserting that none are enabled in production configuration.

T6. Actuator, health, liveness and readiness

  1. Actuator endpoints: health, info, metrics, prometheus, env, configprops, beans, conditions, loggers, threaddump, heapdump, shutdown, startup. Which should be exposed over HTTP in production, on which port, and with what security? Why are env, configprops and heapdump sensitive (secrets in memory and in properties; sanitisation rules)?
  2. Health groups and probes: - liveness ("is the process wedged?": only internal state); - readiness ("can I serve traffic?": includes critical dependencies); - /actuator/health/liveness and /readiness; - health indicators (database, Redis, disk space); - AvailabilityChangeEvent.

What's the cascading-failure risk of putting the database in liveness, or a non-critical dependency in readiness (ch44's gaps)? 3. Design TiffinBox's health model: - which indicators go in readiness (database, yes; the SMS provider, no; payments, degrade instead); - startup probes for slow startup (ch40's warm-up); - readiness during warm-up and shutdown (T4); - showing details only to authorised callers.

T7. Metrics, tracing and observability

  1. Boot's observability stack: Micrometer metrics (timers, counters, gauges, distribution summaries, histograms and percentiles), the auto-instrumented metrics (http.server.requests, JVM, Hikari, executors, caches), Micrometer Observation API (one instrumentation, both metrics and traces), and Micrometer Tracing with OpenTelemetry or Brave (or the OpenTelemetry starter in Boot 4). What do you get for free, and what must you add?
  2. Cardinality. Why must tags be bounded (uri="/orders/{id}", the template, not the actual path; never user ids or order ids as tags)? What happens to Prometheus with unbounded tags? Add a TiffinBox business metric (orders.placed by kitchen_city and payment_method) and an SLO histogram for checkout latency.
  3. Logs, traces and metrics together: trace and span ids in MDC (ch44's T10), exemplars linking metrics to traces, structured logging in Boot 3.4+ (logging.structured.format.console=ecs or logstash), and sampling. Design the dashboards and alerts for the order service (RED metrics per endpoint, saturation of pools, error budget burn: ch52).

T8. Test slices and testing Boot applications

  1. Compare @SpringBootTest (the full context, optionally a real server on a random port) with the slices: - @WebMvcTest (controllers, advice, filters, Jackson; no services); - @DataJpaTest and @JdbcTest (repositories with an embedded or Testcontainers database); - @JsonTest; - @RestClientTest.

What does each load? Why are slices faster, and what can they miss (wiring between layers, security configuration, real serialisation settings)? 2. Mocks and fakes in Boot tests: @MockitoBean (Spring 6.2+, replacing @MockBean), @TestConfiguration fakes, @DynamicPropertySource for Testcontainers ports, and context caching (tests with the same configuration share a context, while every unique @MockitoBean combination creates a new context). How do you keep a suite of 500 tests fast? 3. Configuration tests: ApplicationContextRunner for auto-configurations (P5's three cases), testing property binding and validation (P1), and testing that production profiles have safe settings (T5's leak test).

T9. AOT, native images, startup, images and Boot's peers

  1. The lab's startup numbers: plain JDK server 244 ms (RSS 49 MB); Boot on JDK 21, 3,137 ms (162 MB); lazy initialisation 2,754 ms; JDK 25, 3,080 ms; JDK 25 with an AOT cache, 1,451 ms (150 MB). Explain each option and what it trades: - Spring AOT processing (processAot: bean definitions and reflection hints generated at build time); - GraalVM native images (milliseconds, a closed world); - the JDK's AOT cache (ch39); - CRaC; - lazy initialisation (moves the cost to the first request).
  2. Container images: buildpacks (bootBuildImage), layered JARs with a hand-written Dockerfile (ch42's T9), jlink with distroless. Compare reproducibility, size, control, CVE scanning and native-image support.
  3. Boot's peers: - Micronaut and Quarkus (build-time DI, native-first); - Helidon; - Dropwizard (lightweight composition); - .NET's ASP.NET Core minimal APIs; - NestJS; - Go with chi or Echo; - Python with FastAPI; - Rails and Django (full-stack opinions).

What does each optimise for? What would make TiffinBox move a service off Boot?

Programming exercises

P1. Typed configuration, relaxed binding and silent typos

Bind @ConfigurationProperties("tiffinbox.payments") record PaymentsProps(Duration timeout, DataSize maxBody, List<String> cities, Map<String, Integer> gstByCity) from: - environment variables (including indexed lists); - a command-line map entry; - a deliberately misspelt key.

Print the bound values. Then: - add @Validated with @NotNull and @DurationMin (or the record's compact constructor if Bean Validation isn't available) so a missing timeout fails startup; - write an EnvironmentPostProcessor that warns about unknown tiffinbox.* keys.

P2. JSON strictness in Boot

Post {"dish":"idli","qty":2.9,"coupon":"FREE"} to a Boot 4 controller and observe the lenient result. Then make the API strict: - spring.jackson.deserialization.fail-on-unknown-properties=true; - a JsonMapperBuilderCustomizer disabling float-to-int and string-to-int coercion and enabling strict duplicate detection.

Show the 400 responses (as problem details), and write @JsonTest-style tests (or plain tests with the Boot-configured mapper) for each case.

P3. Errors as problem details everywhere

Show Boot's default error JSON for an unhandled exception and a 404, then the effect of spring.mvc.problemdetails.enabled=true (the 404 converts, the 500 doesn't). Write a @RestControllerAdvice extending ResponseEntityExceptionHandler that: - maps domain exceptions to typed problems with codes; - maps everything else to a generic 500 problem with traceId and no message.

Write a leak test.

P4. Virtual threads and bounded resources in Boot

Run the same endpoint with and without spring.threads.virtual.enabled=true and print the handling thread. Then simulate a 100 ms database call in the handler and load it with 400 concurrent requests: - with platform threads limited to 8 (server.tomcat.threads.max=8); - with virtual threads; - with virtual threads plus a Semaphore(20) bulkhead representing the database pool.

Report p50 and p99, and relate them to ch44's lab and Little's law.

P5. Write an auto-configuration

Write SmsAutoConfiguration registered through AutoConfiguration.imports, with @ConditionalOnMissingBean and @ConditionalOnProperty(matchIfMissing = true), and show the three cases: - the default applies; - it's disabled by property; - a user bean wins.

Read the --debug report entry. Then add @ConditionalOnClass for an optional SDK, typed properties with metadata, and ApplicationContextRunner tests for every case.

P6. Actuator, probes and metrics (expected outputs)

With spring-boot-starter-actuator and micrometer-registry-prometheus (unavailable offline here), configure: - a management port; - exposure of health, info and prometheus; - liveness and readiness groups (readiness including the database and a warm-up indicator); - show-details=when-authorized.

Add: - a business counter (orders.placed with bounded tags); - an SLO histogram; - an @Observed service method.

Write the expected endpoint outputs and a Prometheus query for "checkouts under 300 ms ratio".

P7. Test slices

For the order service, write: - @WebMvcTest tests (status codes, validation problems, JSON shape) with a faked application service; - @JsonTest-style tests for Jackson strictness (P2); - a persistence slice test (@JdbcTest against PostgreSQL via Testcontainers or the local PostgreSQL, previewing ch49); - one @SpringBootTest(RANDOM_PORT) smoke test.

Measure the suite time and the number of contexts created. Then introduce three different @MockitoBean combinations, show the context count rising, and fix it with a shared test configuration.

P8. Graceful shutdown end to end

Reproduce the lab's graceful against immediate shutdown with a 2 s request in flight. Then: - add readiness flipping (AvailabilityChangeEvent) at the start of shutdown; - add a @Scheduled task and a fake message listener (SmartLifecycle) that stop in the right order; - simulate a Kubernetes rolling update (send SIGTERM while a load generator runs) and count client errors.

Write the deployment manifest settings.

P9. Startup: measure and reduce

Measure Boot startup ("Started … in", RSS) for the order service on JDK 21 and JDK 25, then apply in turn: - narrowing component scanning; - excluding unused auto-configurations; - selective lazy beans; - the JDK AOT cache; - Spring AOT processing (-Dspring.aot.enabled=true).

Record each. Optionally build a native image and compare. Relate the results to the lab's 3,137 → 1,451 ms.

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–47)

C1. The order service on Spring Boot

Port ch46's C1 (Spring core wiring) to Spring Boot 4: - starters; - typed properties with validation and the typo detector (P1); - strict JSON (P2); - problem details everywhere (P3); - virtual threads with Hikari sizing and bulkheads (P4); - a custom auto-configuration for TiffinBox defaults (P5); - Actuator probes, metrics and tracing (P6); - test slices (P7); - graceful shutdown (P8); - startup measured (P9); - a layered image (ch42).

Keep the domain module free of Spring (ch46's P7).

Combines: ch42's packaging and images, ch43's modular build, ch44's service fundamentals, ch45's API design and ch46's Spring core, with this chapter.

C2. A TiffinBox platform starter

Build tiffinbox-spring-boot-starter, used by every Boot service. It provides: - strict JSON; - RFC 9457 error handling with codes and traceId; - the request-id filter and structured logging; - HTTP client builders with timeouts and a bulkhead; - Micrometer common tags; - safe Actuator exposure defaults; - the unknown-property warner; - a startup report (versions, configuration summary without secrets).

Each part can be disabled through properties and backs off for user beans. Publish it with semantic versioning and test it with ApplicationContextRunner.

Combines: ch42's library publishing (C1), ch43's convention plugins, ch44's standards (S1), ch45's API style guide (S1), ch46's guidelines (S1), and this chapter's auto-configuration.

C3. Boot against Quarkus against plain Java for the kitchen bridge

Implement ch46's S3 kitchen printer bridge (WebSocket per kitchen, a message consumer, a health endpoint) three ways: - Spring Boot on the JVM plus an AOT cache; - Spring Boot as a native image (or described, if GraalVM is unavailable); - plain Java with the JDK server.

If time allows, add Quarkus. Measure startup, RSS, throughput with 100 kitchen connections, build time and lines of code. Write the decision record.

Combines: ch38's concurrency, ch39's startup features, ch40's runtime, ch41's measurement method, ch44's skeleton, ch46's decision (S3), and this chapter.

What the chapter leaves out

Spring Boot's configuration data API and config servers

spring.config.import loads configuration from config trees (Kubernetes mounted files), extra files, and through extensions from Spring Cloud Config Server, Consul, Vault or AWS Parameter Store. Imports can be optional (optional:), profile-specific and ordered. Runtime refresh (@RefreshScope, Spring Cloud) re-binds properties without restarts, at the cost of complexity and inconsistency windows. Prefer redeploys or feature flags for most changes.

Developer experience features

DevTools (automatic restart through a restart class loader, LiveReload; never in production), Docker Compose support (spring-boot-docker-compose starts services from compose.yaml during development), Testcontainers at development time (TestApplication with @ServiceConnection), and the Boot CLI and Initializr. They shorten the inner loop. Make sure the DevTools class loader (ch40's P3 identity issues) doesn't confuse tests.

Spring Boot upgrade discipline

Boot has releases every six months with roughly a year of open-source support per minor version (longer with commercial support). Major upgrades (2 → 3 meant Jakarta EE; 3 → 4 means Spring Framework 7, Jackson 3, Jakarta EE 11, JSpecify null annotations and removed deprecated APIs) need migration guides, spring-boot-properties-migrator and OpenRewrite recipes. Plan upgrades like JDK upgrades (ch39's C2): CI on the next version, staged rollouts.

Security defaults

Adding spring-boot-starter-security secures every endpoint with a generated password and form login by default, a surprise for API services. Real configuration (resource-server JWT validation, method security, CORS, CSRF for browser clients, the Actuator endpoints' security) is chapter 50's subject. Ensure the management port's security is explicit.

Multi-tenancy and per-tenant configuration

Serving many kitchens or brands from one deployment raises tenant-aware configuration (feature flags per tenant, rate limits per tenant), data isolation (ch49), and observability tags (bounded: the tenant tier, not the tenant id, unless the tenants are few). Boot doesn't solve this. You design it with request context (ch46's T5 cautions), configuration services and data-layer support.

Senior exercises

S1. The Spring Boot service template

Define TiffinBox's Boot service template (a repository template plus the platform starter): - the dependencies (from the platform BOM); - application.yml defaults; - the probes and the Actuator exposure; - strict JSON and problem details; - virtual threads and pool sizing; - graceful shutdown and Kubernetes manifest values; - test layout (unit, slices, smoke); - the observability defaults; - the startup budget and the AOT cache; - the image build; - the upgrade policy.

Tie each choice to an output from this chapter.

S2. Review a Boot application's configuration

A service's application.yml contains: - management.endpoints.web.exposure.include: "*" on the main port; - server.error.include-message: always and include-stacktrace: on_param; - spring.main.lazy-initialization: true in production; - spring.datasource.hikari.maximum-pool-size: 200 with virtual threads enabled; - management.endpoint.health.group.liveness.include: db,redis; - spring.jackson.deserialization.fail-on-unknown-properties: false with a comment "clients send extra stuff"; - secrets inline (razorpay.key: rzp_live_...).

Write the review.

S3. Decide on the observability architecture for Boot services

TiffinBox runs 14 Boot services, a Go worker and a Node BFF. Choose: - the metrics backend (Prometheus with Grafana, or hosted); - tracing (OpenTelemetry with the OTLP collector, sampling strategy); - logs (structured JSON to Loki or OpenSearch); - how Boot services are instrumented (Micrometer with the OTel bridge, the OpenTelemetry Java agent, or Boot 4's OpenTelemetry starter); - the cardinality governance; - the cost controls.

Write the decision.

S4. Teach Boot's defaults with five outputs

Prepare a 20-minute session using: - P1's silently ignored typo; - P2's truncated quantity; - P3's 404 problem against the 500 in the old format; - the lab's liveness versus readiness, and graceful shutdown (2,570 ms against 66 ms); - P5's condition report.

The message: "Boot's defaults are good, and knowing which ones to change is the job".

S5. Plan the Spring Boot 3 to 4 upgrade across the fleet

TiffinBox runs 14 services on Boot 3.3 to 3.5 and JDK 21. Boot 4 brings Spring Framework 7, Jackson 3 (tools.jackson packages), Jakarta EE 11, JSpecify nullness, the removal of deprecated APIs, the removal of Undertow, and new modular auto-configuration JARs. Plan the upgrade, covering: - the order; - the tooling; - the risky areas (Jackson 3 behaviour changes, custom auto-configurations, security configuration, test changes such as @MockBean → @MockitoBean); - the platform starter's role; - the rollout and verification; - the timeline.