Spring Boot 3 and Java 21 Drill-Down on a Small REST Service
System DesignModel answerLast updated
Defend a small Spring Boot 3 / Java 21 REST service: explain startup, auto-configuration, proxies, modern Java features, and design and concurrency trade-offs.
Imagine you have just finished building a compact REST service with Spring Boot 3 on Java 21. It has a few endpoints, a service layer that holds the business rules, a repository (in memory or JPA), and some unit tests. A reviewer now asks you to explain how it works and why you built it that way. Answer with concrete references to your code, and use short snippets where they help.
You may assume a servlet-based Spring MVC stack. State any other assumption you make.
Part 1: Framework mechanics.
Describe what happens between main and the first served request. Cover how the application context is built, how auto-configuration decides which beans exist, how dependency injection wires controller, service and repository, and what proxies and bean scopes mean for annotations such as @Transactional. Explain how you would override or exclude an auto-configured bean.
Part 2: Java 21 in the solution. Choose the Java 21 features that would make the service cleaner or more scalable. Show where each fits and what it replaces. State clearly which features are final in 21, which were finalized earlier, and which are still preview.
Part 3: Defending the design. Justify each layer, describe your test strategy, and explain how the service behaves under concurrent requests. Say what you would change before production, including validation and error handling at the API edge.
Hints
Hint 1
For Part 1, trace the path: `@SpringBootApplication` combines configuration, component scanning and auto-configuration import; then conditions such as `@ConditionalOnMissingBean` filter candidate beans. Then ask what object a caller really holds when a bean carries `@Transactional`.
Hint 2
For Part 2, sort features by release: some were finalized before 21 (records, sealed types, `instanceof` patterns), some are final in 21 (virtual threads, switch patterns, record patterns, sequenced collections), and some are still preview in 21 (string templates, unnamed patterns).
Hint 3
For Part 3, ask what is shared and mutable inside singleton beans, what each test type proves that the others cannot, and what changes when request threads become cheap but the database connection pool stays small.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: What Spring Boot does for you
Startup path. SpringApplication.run creates an application context, prepares the Environment (properties, profiles, env vars), and refreshes the context. @SpringBootApplication is shorthand for three things: @SpringBootConfiguration, @ComponentScan (scans the package of the main class and below for @Component, @Service, @Repository, @RestController) and @EnableAutoConfiguration. For a servlet app, Boot then creates an embedded Tomcat, registers the DispatcherServlet, and starts serving.
Auto-configuration. Boot reads a list of candidate configuration classes from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in each jar. Each class is guarded by conditions:
@ConditionalOnClass: only if a library is on the classpath.@ConditionalOnMissingBean: only if you have not defined your own bean.@ConditionalOnProperty: only if a property is set.
This is why defining your own ObjectMapper or DataSource bean quietly replaces the default. To see why something was or was not configured, run with --debug or use the actuator conditions endpoint. To remove an auto-configuration, use @SpringBootApplication(exclude = ...) or spring.autoconfigure.exclude.
Dependency injection. I use constructor injection, ideally with a single constructor, so no @Autowired is needed:
@Service
class OrderService {
private final OrderRepository repo;
OrderService(OrderRepository repo) { this.repo = repo; }
}
Benefits: dependencies can be final, the object is never half-built, tests need no container (new OrderService(fakeRepo)), and circular dependencies fail fast instead of hiding. Field injection hides dependencies and forces reflection in tests.
Scopes and proxies. Beans are singletons by default: one instance shared by all request threads. @Transactional (and @Cacheable, @Async, method security) works through a proxy, usually CGLIB subclassing in Boot. The caller gets the proxy, which begins the transaction, delegates to the real object, then commits or rolls back. Consequences:
- Self-invocation trap:
this.otherTransactionalMethod()bypasses the proxy, so the annotation does nothing. Fix by moving the method to another bean or restructuring. - Annotated methods must be visible to the proxy (public, non-final); otherwise the advice silently does not apply.
- By default, rollback happens only for unchecked exceptions; checked ones need
rollbackFor.
Part 2: Java 21 features
Final before 21:
- Records (16): immutable DTOs and API payloads, replacing boilerplate classes or Lombok
@Value.record CreateOrder(@NotBlank String sku, @Positive int qty) {}works with Jackson and Bean Validation. - Sealed classes (17): close a hierarchy so the compiler knows all cases.
- Pattern matching for
instanceof(16), switch expressions (14) and text blocks (15).
Final in 21:
- Pattern matching for switch and record patterns, combined with sealed types, give exhaustive handling without a default branch:
sealed interface PaymentResult permits Approved, Declined, Pending {}
record Approved(String txId) implements PaymentResult {}
record Declined(String reason) implements PaymentResult {}
record Pending() implements PaymentResult {}
String message = switch (result) {
case Approved(var id) -> "OK " + id;
case Declined(var reason) -> "Rejected: " + reason;
case Pending p -> "Processing";
};
This replaces instanceof chains and visitor boilerplate. Adding a new subtype turns every non-exhaustive switch into a compile error, which is the real benefit.
- Virtual threads (JEP 444). In a thread-per-request server, blocking I/O no longer ties up an expensive platform thread. In Boot 3.2+ enable them with
spring.threads.virtual.enabled=true. Caveats:- They help I/O-bound work, not CPU-bound work.
- Do not pool them; create one per task.
- In 21, blocking inside
synchronizedpins the carrier thread, so preferReentrantLockaround blocking calls. - Heavy
ThreadLocaluse gets costly with huge thread counts. - Downstream limits (the Hikari pool size, remote rate limits) become the new bottleneck, so more concurrency can just mean longer waits for connections. Use semaphores or bulkheads to protect them.
- Sequenced collections (JEP 431):
getFirst(),getLast()andreversed()onList,Deque,LinkedHashMapand so on, replacing awkwardlist.get(list.size()-1)code.
Still preview in 21: string templates, unnamed patterns and variables (_), unnamed classes with instance main, structured concurrency, scoped values. I would not use them in production code without --enable-preview and a clear reason.
Part 3: Defending the design
Layers. Controller handles HTTP concerns only (mapping, validation, status codes). Service holds business rules and transaction boundaries. Repository hides persistence. I justify each layer by what it lets me test or swap, not by habit. I would not add an interface per class when there is a single implementation, but I would keep one at real seams such as the repository or a payment gateway client.
Concurrency. Singleton beans must be stateless or use safe state. For the in-memory repository I use ConcurrentHashMap and atomic operations (compute, merge, putIfAbsent) rather than check-then-act on a plain map. With JPA, correctness under concurrent updates comes from transactions plus optimistic locking (@Version) or database constraints, not from Java locks.
Testing.
- Plain unit tests for service logic with fake or mocked repositories: fast, no Spring.
@WebMvcTestslice tests for controllers: routing, validation, JSON shape, error mapping.@DataJpaTestfor repository queries, ideally against a real database via Testcontainers rather than H2 when SQL dialects matter.- A few
@SpringBootTesttests for wiring and one end-to-end path per major flow. Keep these few because they are slow.
API boundary. Validate with Bean Validation (@Valid) on request records. Centralize errors in a @RestControllerAdvice that maps domain exceptions to consistent responses (ideally RFC 7807 ProblemDetail) and never leaks stack traces. Use idempotency keys for retried POSTs where duplicates matter.
Before production. Externalize configuration and secrets per profile, add actuator health and metrics, structured logs with correlation IDs, timeouts on every outbound call, database migrations (Flyway or Liquibase), pagination on list endpoints, and load tests that include virtual threads on and off.
Common mistakes
- Calling auto-configuration "magic" instead of naming conditions and the imports file.
- Forgetting the self-invocation problem with
@Transactional. - Claiming string templates or unnamed patterns are final in 21.
- Saying virtual threads make code "faster" rather than more scalable for blocking I/O.
- Keeping mutable state in singleton beans.
- Putting business logic in controllers, then relying only on slow full-context tests.