Prev Next

Java / Java greenfield application best practices in 2026 Interview questions

Last updated

1. What is a greenfield Java application? 2. What is the recommended Java version for a new project in 2026? 3. What are Java records? 4. What are sealed classes and interfaces? 5. What is pattern matching for switch? 6. What are virtual threads? 7. What is Spring Boot 4? 8. What is JSpecify null safety? 9. Define dependency injection? 10. What is hexagonal architecture? 11. What is a modular monolith? 12. What is the purpose of the Optional class? 13. How do you apply immutability in Java code? 14. What is the purpose of DTOs? 15. What is Bean Validation? 16. What is Testcontainers? 17. What is Spring Boot Actuator? 18. What are the pillars of observability? 19. What is a database migration tool? 20. How do you manage configuration and secrets? 21. What is ProblemDetail in Spring? 22. How do you containerize a Java application? 23. What is the purpose of build wrappers and toolchains? 24. How do you enforce code quality in a new project? 25. Why choose Java 25 LTS over Java 27 for production? 26. Why enable compact object headers? 27. When should you choose virtual threads over reactive programming? 28. What happens when a virtual thread is pinned? 29. Why use scoped values instead of ThreadLocal? 30. How does structured concurrency work? 31. Why use constructor injection over field injection? 32. When should you choose a modular monolith over microservices? 33. How do you enforce module boundaries with ArchUnit and Spring Modulith? 34. Why start on Spring Boot 4 instead of Spring Boot 3.5? 35. What is the difference between Jackson 2 and Jackson 3? 36. How does API versioning work in Spring Framework 7? 37. How does built-in resilience work in Spring Framework 7? 38. How do you call external services with HTTP interface clients? 39. Which is better for persistence: JPA, Spring Data JDBC or jOOQ? 40. How do you prevent the N+1 query problem? 41. When should you use @Transactional? 42. How do you choose a garbage collector in 2026? 43. How can you optimize startup time with the AOT cache? 44. When would you choose GraalVM native image? 45. Which is better for builds: Maven or Gradle? 46. How do you structure tests with Testcontainers and slice tests? 47. How do you troubleshoot high memory usage in production? 48. Why use the transactional outbox pattern? 49. How do you secure a new Spring Boot API? 50. How do you manage dependency vulnerabilities and supply chain risk?

1. What is a greenfield Java application?

A greenfield Java application is a new project started from scratch, with no legacy code, inherited database schema or framework choices to work around. You choose the JDK, framework, build tool and architecture yourself.

That freedom is also the risk, because early decisions are expensive to reverse. A sensible day-one baseline covers:

  • a current LTS JDK and a framework on a supported release line
  • a build wrapper and pinned toolchain
  • automated tests and a CI pipeline
  • externalized configuration and secrets handling
  • observability and enforced module boundaries

The opposite is a brownfield project, where you extend or modernize an existing system and compatibility limits your options.

Take quiz
What mainly distinguishes a greenfield project from a brownfield one?
It must be built as microservices
It can only target non-LTS JDK releases
It starts with no legacy code or inherited technology constraints
Why are early decisions so important on a greenfield Java project?
They are locked by the JVM specification
They only affect the project folder layout
Build tools refuse to change them after the first release
Changing the JDK, framework or architecture later usually touches the whole codebase

Start on Java 25, the current long-term support (LTS) release, which shipped in September 2025. It gives you finalized virtual threads, scoped values, compact object headers as a product feature and years of vendor patch updates.

Release Date Type
Java 21 Sep 2023 LTS
Java 25 Sep 2025 LTS (recommended baseline)
Java 26 Mar 2026 Non-LTS, 6 months of updates
Java 27 Sep 15, 2026 Non-LTS
Java 29 Sep 2027 (planned) Next LTS

Run Java 27 in a CI matrix job so upgrades stay boring, but keep production on the LTS unless you can move every six months. Always confirm your framework's supported-JDK matrix first.

3. What are Java records?

A record is a concise class for immutable data. You declare the components, and the compiler generates the private final fields, canonical constructor, accessors, equals, hashCode and toString.

public record Money(BigDecimal amount, String currency) {
    public Money {                       // compact constructor
        Objects.requireNonNull(amount);
        if (currency.length() != 3) throw new IllegalArgumentException("ISO code expected");
    }
}

Records can implement interfaces but cannot extend classes. They are shallowly immutable: if a component is a mutable List, wrap it with List.copyOf in the compact constructor. Use them for DTOs, value objects, events and configuration properties, not for JPA entities.

Take quiz
Which limitation applies to a Java record?
It cannot extend another class
It cannot implement interfaces
It cannot declare a constructor
It cannot have accessor methods
How do you stop a record's List component from being modified by outsiders?
Add the volatile keyword to the component
Copy it with List.copyOf in the compact constructor
Mark the record class abstract
Nothing is needed, records deep-freeze their fields

4. What are sealed classes and interfaces?

A sealed type restricts which classes may extend or implement it, using a permits clause. It was finalized in Java 17.

public sealed interface PaymentResult permits Approved, Declined, Pending {}
public record Approved(String authCode) implements PaymentResult {}
public record Declined(String reason) implements PaymentResult {}
public record Pending(Instant retryAt) implements PaymentResult {}

Each permitted subtype must be declared final, sealed or non-sealed. The payoff is that the compiler knows every possible subtype, so a switch over the type needs no default branch and breaks at compile time when you add a new case.

Take quiz
What must every permitted subtype of a sealed type be declared as?
public, private or protected
final, sealed or non-sealed
abstract, static or default
volatile, transient or strictfp
What benefit do sealed hierarchies give to switch expressions?
They allow switching on mutable fields
They make the switch run on virtual threads
The compiler can check exhaustiveness without a default branch
They remove the need for pattern matching

5. What is pattern matching for switch?

Pattern matching for switch (final in Java 21) lets a switch test the type and shape of a value, bind it to a variable and add a guard with when. It replaces long instanceof and cast chains.

static String describe(PaymentResult r) {
    return switch (r) {
        case Approved a              -> "approved " + a.authCode();
        case Declined(String reason) -> "declined: " + reason;   // record pattern
        case Pending p when p.retryAt().isBefore(Instant.now()) -> "overdue";
        case Pending p               -> "pending";
    };
}

Combined with sealed types, the switch is exhaustive, so adding a new PaymentResult subtype produces a compile error where it is not handled. Place guarded cases before the unguarded one for the same type.

Take quiz
What does the when keyword do inside a pattern switch case?
Imports a record pattern from another file
Declares a new thread for the case
Adds a boolean guard to the pattern
Marks the case as the default branch
Why combine pattern switch with a sealed hierarchy?
It turns the switch into a lookup table at runtime
It lets the JVM skip bytecode verification
It makes the switch fall through safely
Missing subtypes become compile-time errors

6. What are virtual threads?

Virtual threads are lightweight threads managed by the JVM rather than the OS. They were finalized in Java 21 (Project Loom). When a virtual thread blocks on I/O, the JVM unmounts it from its carrier thread so that carrier can run other work.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (var id : orderIds) {
        executor.submit(() -> inventoryClient.reserve(id));   // blocking call is fine
    }
}

Create one per task and never pool them. In Spring Boot, set spring.threads.virtual.enabled=true to serve requests on virtual threads. They help blocking, I/O-bound code scale; they do nothing for CPU-bound work.

Take quiz
How should you use virtual threads with an executor?
Share one virtual thread across all requests
Pool a fixed number of them like platform threads
Pin each one to a CPU core
Create a new virtual thread per task and do not pool them
Which workload benefits most from virtual threads?
Blocking I/O-bound request handling
Tight CPU-bound number crunching
Single-threaded startup code
Native memory allocation

7. What is Spring Boot 4?

Spring Boot 4 (November 2025) is the major release built on Spring Framework 7 and Jakarta EE 11 with a Servlet 6.1 baseline. The minimum JDK is still 17, and Java 25 is fully supported.

Headline changes for a new project:

  • modularized codebase with smaller, technology-specific starters
  • Jackson 3 as the default JSON library
  • JSpecify null-safety annotations across the framework
  • built-in API versioning and resilience features (retry, concurrency limit)
  • Undertow removed and JUnit 4 support dropped

Spring Boot has no LTS line. Minor versions arrive roughly every six months with about 12 months of open-source support, so plan regular upgrades.

Take quiz
Which Jakarta EE baseline does Spring Boot 4 use?
Jakarta EE 11
Jakarta EE 10
Jakarta EE 9
Java EE 8
Which JSON library is the default in Spring Boot 4?
Gson
Jackson 3
JSON-B
Jackson 2 only

8. What is JSpecify null safety?

JSpecify is a standard set of null-safety annotations for Java, in org.jspecify.annotations. Spring Framework 7 adopted it and replaced its older org.springframework.lang annotations.

The model is simple: inside a @NullMarked package or class, every type is non-null unless marked @Nullable.

@NullMarked
package com.acme.orders;

public interface CustomerLookup {
    @Nullable Customer findByEmail(String email);   // may return null
    Customer getById(long id);                       // never null
}

The annotations do nothing at runtime. They pay off when a checker such as NullAway (via Error Prone) runs in the build, so null bugs fail compilation instead of surfacing as NullPointerException in production.

Take quiz
What does @NullMarked mean in JSpecify?
Null checks are inserted at runtime
Types in that scope are non-null unless marked @Nullable
The class is excluded from compilation
Every value in scope may be null
How do JSpecify annotations prevent NullPointerExceptions?
They wrap values in Optional automatically
They are validated by Bean Validation on every request
A build-time checker such as NullAway uses them to fail compilation
The JVM throws them as checked exceptions

9. Define dependency injection?

Dependency injection (DI) means an object receives the collaborators it needs from outside instead of creating them itself. In Spring, the container builds the objects, wires them and manages their lifecycle.

@Service
class InvoiceService {
    private final InvoiceRepository repository;
    private final TaxClient taxClient;

    InvoiceService(InvoiceRepository repository, TaxClient taxClient) {
        this.repository = repository;
        this.taxClient = taxClient;
    }
}

Because dependencies are passed in, a unit test can hand the class a fake TaxClient without starting Spring. DI also keeps business code coupled to interfaces, not to concrete implementations or construction details.

Take quiz
In dependency injection, who creates the collaborators of a class?
The garbage collector
The class itself in its static initializer
An external container or caller passes them in
The compiler at build time
What testing advantage does DI give InvoiceService?
The class becomes thread-safe automatically
Tests no longer need assertions
Mocking frameworks become unnecessary for integration tests
You can pass a fake TaxClient to the constructor without Spring

10. What is hexagonal architecture?

Hexagonal architecture (ports and adapters) keeps business logic in a core that knows nothing about frameworks, databases or HTTP. The core defines ports (interfaces) and the outside world plugs in through adapters.

flowchart LR
  A["REST controller<br/>inbound adapter"] --> B["Inbound port<br/>use case interface"]
  B --> C((Domain core))
  C --> D["Outbound port<br/>OrderRepository"]
  D --> E["JPA adapter"]
  D --> F["Message publisher adapter"]

In a Spring project this usually means a domain package with no Spring or JPA imports, plus adapter.in.web and adapter.out.persistence packages. Dependencies always point inward. You can then swap PostgreSQL for another store or test the core with in-memory adapters.

Take quiz
In hexagonal architecture, which direction do source-code dependencies point?
Outward, from the core to adapters
Between adapters only
Toward the database layer
Inward, toward the domain core
What is a port?
An interface owned by the core that adapters implement or call
A Spring Boot configuration property
A network socket opened by the JVM
A JPA entity manager

11. What is a modular monolith?

A modular monolith is a single deployable application split into well-bounded modules, each owning its own data and exposing a small public API. Other modules cannot reach into its internals.

It gives most of the design benefits of microservices, such as clear ownership and low coupling, without network calls, distributed transactions or a fleet of pipelines to run.

In Java, modules are typically top-level packages (for example orders, billing, inventory). Spring Modulith or ArchUnit tests then verify that no module touches another's internal packages. Modules talk through public interfaces or application events, which also makes later extraction into a service realistic.

Take quiz
How many deployable units does a modular monolith have?
One
One per database table
One per module
One per team plus a gateway
How should modules in a modular monolith communicate?
By reading each other's private fields via reflection
Through public APIs or application events, not internal classes
By sharing each other's repositories directly
Only through HTTP calls on localhost

12. What is the purpose of the Optional class?

Optional<T> is a return-type wrapper that tells the caller a value may be absent, so they cannot forget to handle it. It is not a general replacement for null.

return userRepository.findByEmail(email)
        .map(User::displayName)
        .orElseThrow(() -> new UserNotFoundException(email));

Guidelines that hold up in reviews:

  • use it as a return type for lookups that may find nothing
  • do not use it for fields, method parameters or collection elements
  • return an empty collection, never Optional<List<T>>
  • avoid bare get(); use orElseThrow, map or ifPresent
Take quiz
Where is Optional intended to be used?
As a parameter on all public methods
As a method return type that may have no result
As a replacement for empty collections
As a field type in every entity
Which call is preferred over a bare Optional.get()?
getOrNull
Optional.toString
orElseThrow with a meaningful exception
unwrapUnsafe

13. How do you apply immutability in Java code?

Make objects unchangeable after construction, so they can be shared across threads and cannot drift into invalid states.

  1. Prefer records or classes with final fields and no setters.
  2. Copy mutable inputs in the constructor with List.copyOf, Set.copyOf or Map.copyOf.
  3. Return unmodifiable collections instead of internal ones.
  4. Use java.time types and BigDecimal, which are already immutable.
  5. Model changes as new instances, for example order.withStatus(PAID).

A common trap: Collections.unmodifiableList(list) is only a read-only view. If someone still holds the original list, the contents can change. List.copyOf takes a real snapshot.

Take quiz
Why is Collections.unmodifiableList(list) not a full immutability guarantee?
It throws on every read
It copies the list deeply on each call
It is a read-only view, so changes to the original list still show through
It only works with arrays
Which approach correctly models a change to an immutable Order?
Use reflection to rewrite the final field
Call a setter on the existing object
Mark the object volatile and update it
Return a new instance with the changed field

14. What is the purpose of DTOs?

A Data Transfer Object defines the shape of data crossing a boundary, usually your REST API, separate from your persistence entities.

Exposing JPA entities directly couples your public contract to your table design. It can also trigger lazy loading during JSON serialization, leak internal fields and create infinite loops in bidirectional relations.

In 2026 DTOs are normally records:

public record OrderResponse(UUID id, String status, BigDecimal total) {
    static OrderResponse from(Order o) {
        return new OrderResponse(o.getId(), o.getStatus().name(), o.getTotal());
    }
}

Map manually for small models or generate mappers with MapStruct for larger ones. Version request and response types independently from the entity.

Take quiz
What is the main reason to avoid returning JPA entities from a REST API?
Entities cannot be serialized to JSON in any form
It forces the API to use SOAP
Entities are always larger than 1 MB
It couples the API contract to the persistence model and can trigger lazy loading
Which Java construct is the usual choice for DTOs today?
Records
Static nested interfaces
Enums
Abstract classes

15. What is Bean Validation?

Bean Validation (Jakarta Validation, implemented by Hibernate Validator) declares constraints with annotations such as @NotBlank, @Email, @Size and @Positive, then enforces them automatically.

public record CreateUserRequest(
        @NotBlank @Size(max = 80) String name,
        @Email @NotBlank String email,
        @Min(18) int age) {}

@PostMapping("/users")
ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest req) { ... }

When validation fails, Spring rejects the request with a 400 before your controller logic runs. Add the validation starter, validate at the boundary, and keep domain invariants in the domain model as well, since not every entry point goes through a controller.

Take quiz
Which annotation on a controller parameter triggers Bean Validation?
@Valid
@Verify
@Transactional
@Checked
What status does Spring typically return when a @Valid request body fails validation?
204 No Content
400 Bad Request
404 Not Found
500 Internal Server Error

16. What is Testcontainers?

Testcontainers is a library that starts real services, such as PostgreSQL, Kafka or Redis, in disposable Docker containers for the duration of a test.

It removes the classic gap between an in-memory database like H2 and production behavior: same SQL dialect, same constraints, same locking. In Spring Boot, @ServiceConnection on the container field wires the connection details into the application context automatically, with no manual property overrides.

The cost is startup time and the need for a container runtime in CI. Reuse one container across test classes and keep the number of full-context tests small to keep the suite fast.

Take quiz
What does Testcontainers start for each test run?
An embedded JVM per test method
Real dependencies in disposable Docker containers
Mock objects generated by bytecode
A copy of the production cluster
What does @ServiceConnection do in Spring Boot tests?
Opens a firewall port on the host
Pools the container across all projects
Wires the container's connection details into the app context automatically
Replaces JUnit assertions

17. What is Spring Boot Actuator?

Actuator adds production-ready endpoints to a Spring Boot app, most importantly /actuator/health, /actuator/metrics, /actuator/info and, when enabled, /actuator/sbom.

For Kubernetes, enable the liveness and readiness probes. Liveness answers whether the process should be restarted; readiness answers whether it should receive traffic. Do not include slow downstream checks in liveness, or a database outage will restart healthy pods.

management.endpoints.web.exposure.include=health,info,prometheus
management.endpoint.health.probes.enabled=true

Expose only what you need, and put the management port behind your network policy or a separate port.

Take quiz
What question does a Kubernetes readiness probe answer?
Whether the JVM heap is below 50 percent
Whether the build passed in CI
Whether the instance should receive traffic
Whether the container image is signed
Why should liveness probes avoid checking the database?
Databases never report health
Liveness probes cannot make network calls
It would disable Actuator metrics
A database outage would restart healthy application instances

18. What are the pillars of observability?

Observability rests on three signals that answer different questions about a running system.

Signal Answers Typical tooling
Logs What happened in detail? Structured JSON logs, Loki, ELK
Metrics How is it behaving over time? Micrometer, Prometheus
Traces Where did this request spend time? OpenTelemetry, Tempo, Jaeger

Spring Boot uses Micrometer for metrics and tracing instrumentation, exports through OpenTelemetry, and supports structured log formats such as ECS and Logstash out of the box. Include a trace ID in every log line so you can jump from a failing trace to its logs.

Take quiz
Which signal shows where a single request spent its time across services?
Build logs
Metrics
Heap dumps
Traces
Which library does Spring Boot use as its metrics facade?
Micrometer
Hystrix
Log4Shell
Dropwizard Pool

19. What is a database migration tool?

A migration tool such as Flyway or Liquibase applies versioned schema changes in order and records what has run, so every environment ends up with the same schema.

With Flyway, you add files like V3__add_invoice_status.sql under db/migration. On startup it applies any not-yet-run versions and stores checksums in its history table.

  • never edit a migration that has already been applied; add a new one
  • set spring.jpa.hibernate.ddl-auto to validate or none outside local experiments
  • make changes backward compatible (expand, migrate, contract) so old and new app versions can overlap during deploys
  • in Spring Boot 4, include the dedicated Flyway or Liquibase starter
Take quiz
What should you do when a Flyway migration has already run in production and needs a fix?
Add a new migration with the correction
Delete the history table
Edit the existing file and redeploy
Set ddl-auto to create-drop
Which Hibernate ddl-auto setting is appropriate outside local development?
update
validate or none
create
create-drop

20. How do you manage configuration and secrets?

Keep configuration outside the artifact and secrets outside the repository.

  1. Put defaults in application.yaml and override per environment with environment variables or profile files.
  2. Bind groups of settings to a validated record with @ConfigurationProperties.
  3. Load secrets from a secret manager (Vault, AWS or GCP Secret Manager, Kubernetes secrets) using spring.config.import or injected env vars.
  4. Never commit credentials, and rotate them without rebuilding the image.
@ConfigurationProperties("billing")
@Validated
public record BillingProperties(@NotBlank String apiUrl, @DefaultValue("5s") Duration timeout) {}

Failing fast on missing or invalid properties at startup is far cheaper than discovering them at the first request.

Take quiz
Why bind settings to a @Validated @ConfigurationProperties record?
It lets the JVM skip classloading
Missing or invalid values fail at startup instead of at runtime
It encrypts the values at rest
It removes the need for environment variables
Where should production database passwords live?
In the Dockerfile as an ENV line
In application.yaml committed to Git
In a secret manager or injected environment, never in the repository
In a README in the root folder

21. What is ProblemDetail in Spring?

ProblemDetail is Spring's representation of RFC 9457 (which superseded RFC 7807), a standard JSON format for HTTP API errors with media type application/problem+json.

{
  "type": "https://api.acme.com/errors/insufficient-funds",
  "title": "Insufficient funds",
  "status": 422,
  "detail": "Balance 10.00 is below the required 25.00",
  "instance": "/payments/8841"
}

Extend ResponseEntityExceptionHandler in a @RestControllerAdvice to get consistent problem responses for framework exceptions, and add your own handlers returning ProblemDetail for domain errors. A single error shape means clients write one parser, and you avoid leaking stack traces.

Take quiz
Which media type does a ProblemDetail response use?
text/error
application/xml+problem
application/problem+json
application/json-error
What is the benefit of using ProblemDetail across an API?
It encrypts error responses
It disables logging of exceptions
It forces all errors to return HTTP 200
Clients get one standard error shape instead of ad hoc messages

22. How do you containerize a Java application?

You have three solid options, and all of them should produce a small image that runs as a non-root user.

  • Cloud Native Buildpacks: ./mvnw spring-boot:build-image needs no Dockerfile and applies sensible JVM memory settings.
  • Jib: builds layered images without a Docker daemon.
  • Multi-stage Dockerfile: build with a JDK image, run on a JRE image such as a Java 25 runtime.

Whichever you choose, extract the jar into layers (java -Djarmode=tools -jar app.jar extract --layers) so dependency layers cache between builds. Rely on the JVM's container awareness with -XX:MaxRAMPercentage=75 instead of a hard-coded -Xmx, and send logs to stdout.

Take quiz
Why extract a Spring Boot jar into layers for the image?
It removes the need for a JDK
It makes the JVM skip garbage collection
It encrypts class files
Dependency layers stay cached when only application code changes
Which JVM flag sizes the heap relative to the container memory limit?
-XX:MaxRAMPercentage
-XX:UseContainerLogs
-Xnative
-XX:HeapFromNetwork

23. What is the purpose of build wrappers and toolchains?

The Maven Wrapper (mvnw) and Gradle Wrapper (gradlew) pin the exact build tool version in the repository, so every developer and CI agent builds with the same one without installing it.

Toolchains do the same for the JDK. In Gradle:

java {
    toolchain { languageVersion = JavaLanguageVersion.of(25) }
}

In Maven, set maven.compiler.release to 25 and use the toolchains plugin when you need a specific JDK vendor. Together, they remove the classic works on my machine problem caused by mismatched build tool or JDK versions.

Take quiz
What does the Gradle or Maven wrapper pin?
The build tool version used for the project
The database schema version
The Git branch
The Docker base image
What problem do JDK toolchains solve?
They compress the final jar
Builds use the same JDK version on every machine
They generate unit tests
They install JDK patches into production

24. How do you enforce code quality in a new project?

Automate every rule you care about so reviews can focus on design.

Concern Tool
Formatting Spotless (google-java-format or Palantir)
Null safety Error Prone with NullAway and JSpecify
Bug patterns Error Prone, SpotBugs
Style rules Checkstyle
Architecture rules ArchUnit, Spring Modulith verification
Coverage and smells JaCoCo, SonarQube

Turn warnings into errors with -Xlint:all -Werror from day one, since it is far harder to add later. Run the checks in CI as a required gate and let the formatter run in a pre-commit hook or IDE on save.

Take quiz
Which tool pair can enforce null-safety at compile time?
JaCoCo with Checkstyle
Error Prone with NullAway
Spotless with Flyway
Testcontainers with Mockito
Why enable -Werror from the first commit?
It is required by Maven Central
It removes the need for tests
Adding it later to a codebase full of warnings is much harder
It makes the JVM start faster

25. Why choose Java 25 LTS over Java 27 for production?

Because support horizon matters more than novelty for most services. Java 25 is an LTS release with multi-year patch updates, while Java 27 (released September 15, 2026) is a non-LTS release that is superseded after about six months.

Java 27 does bring useful changes, such as compact object headers and G1 as the default collector everywhere. But the features that most affect application design, virtual threads, scoped values and compact headers as a product feature, are already available on 25.

  • fewer forced upgrades: the next LTS is Java 29, planned for September 2027
  • framework and library matrices target LTS first; confirm your Spring Boot and library versions before moving
  • vendor builds of non-LTS releases get security fixes only until the next release

A practical policy: ship on 25, test every new release in CI, and jump to the next LTS once your dependencies support it.

Take quiz
Why do many teams keep production on Java 25 rather than Java 27?
Java 25 has newer language features than 27
Non-LTS releases cannot use virtual threads
Java 25 is LTS with a longer patch-update horizon
Java 27 cannot run Spring Boot at all
Which release is the next planned LTS after Java 25?
Java 30
Java 27
Java 28
Java 29

26. Why enable compact object headers?

Every Java object carries a header. Compact object headers shrink it from 16 bytes to 12 bytes on 64-bit HotSpot, which cuts heap use and improves cache locality for applications with many small objects.

It became a product feature in Java 25 (JEP 519) and is on by default in Java 27 (JEP 534). On Java 25 you opt in:

java -XX:+UseCompactObjectHeaders -jar app.jar

Reported gains are roughly 10 to 20 percent less heap and a modest throughput increase, but results depend on your object mix. Measure with your own load test and GC logs before relying on the number.

A caveat is that code that depends on header layout, such as some agents or native tools, should be tested first.

Take quiz
By how much do compact object headers shrink a typical 64-bit object header?
They remove the header entirely
From 12 bytes to 8 bytes
From 32 bytes to 16 bytes
From 16 bytes to 12 bytes
When are compact object headers enabled by default?
Java 27
Java 17
Java 21
Java 25

27. When should you choose virtual threads over reactive programming?

Choose virtual threads when the workload is mostly blocking I/O and you want simple, debuggable, imperative code. Choose reactive when you need streaming with backpressure or an end-to-end non-blocking pipeline.

Concern Virtual threads Reactive (WebFlux)
Code style Plain blocking code Operator chains, Mono/Flux
Stack traces Normal and readable Hard to follow
Backpressure None built in First-class
Learning curve Low High
Best fit CRUD and service calls Streams, SSE, fan-out

Virtual threads remove the thread limit, not the downstream limit. A database pool of 20 connections is still 20, so cap concurrency with a Semaphore or pool size to avoid piling thousands of waiters on a slow dependency. Most new CRUD-style services are simpler on virtual threads.

Take quiz
Which need still favors reactive programming over virtual threads?
Streaming with built-in backpressure
Simple blocking CRUD endpoints
Readable stack traces
Calling a JDBC driver
Why might you still limit concurrency when using virtual threads?
The JVM forbids more than one per CPU core
Downstream resources like connection pools have fixed capacity
Garbage collection stops when too many exist
Virtual threads crash above 1000 instances

28. What happens when a virtual thread is pinned?

A pinned virtual thread cannot unmount from its carrier thread when it blocks, so it holds that platform thread. Enough pinned threads can starve the carrier pool and stall throughput.

Before Java 24, blocking inside a synchronized block was the main cause. JEP 491 (Java 24) fixed that: virtual threads can now acquire and release monitors without pinning. Today, pinning mostly comes from:

  • a native frame on the stack, such as JNI or a foreign function call
  • class initialization that is waiting on another thread

To find it, record a JFR profile and look for the jdk.VirtualThreadPinned event. If pinning shows up, shorten the work done in the native call, or move the blocking part out of it. On an LTS Java 25 baseline, the old advice to rewrite every synchronized to ReentrantLock is no longer needed.

Take quiz
What does pinning mean for a virtual thread?
It is permanently converted to a platform thread
It cannot unmount from its carrier thread while blocked
It runs at higher priority than platform threads
It skips garbage collection
Which JFR event reveals pinned virtual threads?
jdk.MonitorStall
jdk.ThreadSleep
jdk.VirtualThreadPinned
jdk.CarrierDump

29. Why use scoped values instead of ThreadLocal?

Scoped values (final in Java 25) share immutable data with a bounded section of code and everything it calls, then disappear automatically. ThreadLocal has no such boundary.

static final ScopedValue<User> CURRENT_USER = ScopedValue.newInstance();

ScopedValue.where(CURRENT_USER, user).run(() -> handleRequest());
// anywhere below: CURRENT_USER.get()

Why it matters, especially with virtual threads:

  • no cleanup: values vanish when the scope ends, so no leaks into reused threads
  • immutable: callees cannot rebind it, which avoids hidden mutation
  • cheap: they avoid the per-thread map cost when you create millions of virtual threads
  • inherited by forked subtasks in structured concurrency

Existing frameworks still rely on ThreadLocal for things like security context and MDC, so in application code, prefer scoped values for new request-scoped data and leave framework internals alone.

Take quiz
What is a key property of a ScopedValue binding?
It is stored in a global static map
It can be reassigned by any thread at any time
It is immutable and limited to a bounded scope
It lives until the JVM shuts down
Which problem of ThreadLocal do scoped values avoid?
Forced use of synchronized blocks
Inability to store strings
Lack of generics support
Values leaking into reused threads because nobody cleaned them up

30. How does structured concurrency work?

Structured concurrency treats a group of concurrent subtasks as one unit of work. The parent opens a scope, forks subtasks, waits for them, and cannot leave the scope until they have all finished or been cancelled.

try (var scope = StructuredTaskScope.open()) {
    var user   = scope.fork(() -> userClient.load(id));
    var orders = scope.fork(() -> orderClient.load(id));
    scope.join();                                   // waits, propagates failure
    return new Profile(user.get(), orders.get());
}

flowchart TD
  P["Parent opens scope"] --> F1["fork: load user"]
  P --> F2["fork: load orders"]
  F1 --> J[join]
  F2 --> J
  J --> R["Return result or cancel siblings on failure"]

A failing subtask can cancel its siblings, so no thread is left running after the method returns. This API is still a preview feature (seventh preview in Java 27), so it needs --enable-preview and its API may change between releases. Treat it as experimental in production code.

Take quiz
What guarantee does a structured concurrency scope give?
Subtasks ignore cancellation
Subtasks always run on separate processes
Results are cached across requests
Subtasks cannot outlive the scope that forked them
What is the status of StructuredTaskScope in Java 27?
Preview feature requiring --enable-preview
Deprecated for removal
Finalized and enabled by default
Removed from the JDK

31. Why use constructor injection over field injection?

Constructor injection makes dependencies explicit, final and testable. Field injection with @Autowired hides them inside the class.

Aspect Constructor injection Field injection
Immutability Fields can be final Fields must be mutable
Unit testing new Service(fake) Needs reflection or Spring
Required deps Object cannot exist without them Can be left null
Circular deps Fail fast at startup Often hidden
Boilerplate None with a single constructor Short, but opaque

With one constructor, Spring needs no @Autowired. A constructor with six or seven parameters is also useful feedback that the class has too many responsibilities.

Take quiz
What can constructor injection do that field injection cannot?
Let dependencies be declared final
Avoid the Spring container entirely
Inject beans after startup
Skip dependency resolution
What does a constructor with many parameters usually signal?
Spring cannot instantiate it
The class may have too many responsibilities
The class should use field injection
The bean should be a singleton

32. When should you choose a modular monolith over microservices?

Choose a modular monolith by default for a new product, especially while the domain is still being discovered and the team is small. Choose microservices when you have a concrete reason that a single deployable cannot meet.

Factor Modular monolith Microservices
Team size One or a few teams Many autonomous teams
Deploy One pipeline Independent pipelines
Scaling Scale the whole app Scale hot services alone
Consistency Local transactions Eventual consistency, sagas
Operations Simple Service mesh, tracing, versioning
Boundary cost Cheap to move Costly to move

Good reasons to split: very different scaling profiles, regulatory isolation, or teams that block each other's releases. Because modules already have public APIs and own their data, extracting one later is a planned step rather than a rewrite.

Take quiz
Which situation is a good reason to extract a module into its own microservice?
Local transactions feel too safe
One module has a very different scaling profile from the rest
The package names are long
The team prefers a new framework logo
Why start a new product as a modular monolith?
It removes the need for tests
Monoliths cannot have module boundaries
Domain boundaries are cheap to change while the domain is still being discovered
Microservices cannot use Java

33. How do you enforce module boundaries with ArchUnit and Spring Modulith?

Boundaries only last if the build fails when someone crosses them. Two tools cover this.

Spring Modulith treats each direct sub-package of your application's main package as a module and verifies the structure in a test:

class ModularityTests {
    @Test
    void verifyModules() {
        ApplicationModules.of(Application.class).verify();   // fails on cycles and internal access
    }
}

Only the module's base package is its public API; classes in sub-packages stay internal. Modules can talk via public services or @ApplicationModuleListener events, and the same model can generate documentation diagrams.

ArchUnit handles custom rules, for example that the domain package never imports Spring or JPA:

noClasses().that().resideInAPackage("..domain..")
    .should().dependOnClassesThat().resideInAnyPackage("org.springframework..", "jakarta.persistence..")
    .check(importedClasses);

Take quiz
What does ApplicationModules.of(Application.class).verify() check?
That database migrations are applied
That every class has a Javadoc comment
That modules have no cycles and do not access each other's internals
That all tests pass in under a second
What would an ArchUnit rule on the domain package typically forbid?
Using records
Declaring final fields
Writing unit tests
Dependencies on Spring or JPA classes

34. Why start on Spring Boot 4 instead of Spring Boot 3.5?

Because Spring Boot 3.x is on its way out and a new project should not begin with a migration already due. Open-source support for Spring Boot 3.5 ended on June 30, 2026, and 3.4 ended earlier.

What a new project gets from the 4.x line:

  • Spring Framework 7 and Jakarta EE 11, with Hibernate and Spring Security versions aligned
  • built-in API versioning and resilience annotations, so fewer extra libraries
  • JSpecify null-safety across the framework
  • Jackson 3 as the default, which is the library's long-term direction
  • support for Java 25, with the same Java 17 minimum as 3.x

Spring Boot has no LTS releases, so you upgrade the minor version about twice a year regardless. Starting on the newest GA 4.x line avoids skipping a major migration later. Check the project's support timeline page for the current dates.

Take quiz
What happened to open-source support for Spring Boot 3.5 on June 30, 2026?
It switched to Jakarta EE 12
It was extended to 2030
It became the LTS line
It ended
Which statement about Spring Boot LTS releases is true?
Spring Boot does not designate LTS versions
LTS follows the Java LTS schedule exactly
Every even-numbered minor is LTS
Only 3.5 is LTS

35. What is the difference between Jackson 2 and Jackson 3?

Jackson 3 is a major rewrite adopted as the default by Spring Boot 4. The visible changes for application code are these:

Area Jackson 2 Jackson 3
Core and databind package com.fasterxml.jackson.* tools.jackson.*
Annotations package com.fasterxml.jackson.annotation unchanged (same package)
Mapper Mutable ObjectMapper Immutable, built via JsonMapper.builder()
Exceptions Checked IOException family Unchecked JacksonException
Date and time Needs a JavaTime module Built in, ISO strings by default
Java baseline 8 17

Spring Boot 4 keeps a deprecated Jackson 2 compatibility path for migration, but a greenfield app should use Jackson 3 only and avoid mixing both in one classpath. Because annotations kept their package, your @JsonProperty and @JsonIgnore usages mostly carry over.

Take quiz
How is a Jackson 3 mapper typically created?
With JsonMapper.builder() producing an immutable mapper
By extending a JSON schema class
Through a Maven plugin
By calling new ObjectMapper().setMutable(true)
What happens to Jackson's annotation package in version 3?
It becomes jakarta.json
It stays com.fasterxml.jackson.annotation
It moves to tools.jackson.annotation
It is removed

36. How does API versioning work in Spring Framework 7?

Spring Framework 7 adds first-class API versioning. You mark mappings with a version and configure how the client sends it.

@RestController
@RequestMapping("/orders")
class OrderController {
    @GetMapping(version = "1.0") OrderV1 getV1(...) { ... }
    @GetMapping(version = "1.1+") OrderV2 getV2(...) { ... }   // 1.1 and above
}

@Configuration
class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureApiVersioning(ApiVersionConfigurer c) {
        c.useRequestHeader("API-Version").addSupportedVersions("1.0", "1.1").setDefaultVersion("1.0");
    }
}

The version can be resolved from a request header, a path segment, a query parameter or a media type parameter. A trailing + means this version and later, which avoids copying handlers for unchanged endpoints. Choose one strategy for the whole API and document the deprecation policy for old versions.

Take quiz
What does a mapping version such as "1.1+" mean?
Exactly version 1.1 only
Version 1.1 and later
Any version below 1.1
Version 1.1 with debug logging
Which of these is a supported way to carry the API version?
Only a cookie
Only the HTTP method
A request header, path segment, query parameter or media type parameter
Only the JSON body

37. How does built-in resilience work in Spring Framework 7?

Spring Framework 7 ships core retry and concurrency-limit support, so you no longer need the separate spring-retry library for simple cases. Enable it once and annotate methods.

@Configuration
@EnableResilientMethods
class ResilienceConfig {}

@Service
class RatesClient {
    @Retryable(includes = IOException.class, maxRetries = 3, delay = 200, multiplier = 2)
    BigDecimal fetchRate(String pair) { ... }

    @ConcurrencyLimit(10)           // at most 10 concurrent callers
    Report heavyReport() { ... }
}

@Retryable supports delay, jitter, multiplier and exception filters; there is also a programmatic RetryTemplate. @ConcurrencyLimit works as a bulkhead and pairs well with virtual threads.

It does not include a circuit breaker or rate limiter, so use Resilience4j or a gateway for those. Only retry idempotent operations.

Take quiz
Which annotation enables Spring's built-in resilience features?
@EnableCircuitBreakerAuto
@ResilienceBoot
@EnableResilientMethods
@EnableRetryEverywhere
What does @ConcurrencyLimit(10) do?
Limits the method to ten database rows
Caches ten results
Retries the method ten times
Allows at most ten concurrent callers into the method

38. How do you call external services with HTTP interface clients?

Declare the remote API as a Java interface with @HttpExchange annotations and let Spring generate the implementation on top of RestClient.

@HttpExchange("/rates")
interface RatesApi {
    @GetExchange("/{pair}")
    Rate get(@PathVariable String pair);
}

In Spring Framework 7 and Boot 4, register such interfaces with @ImportHttpServices and group them, so base URLs and timeouts are set through configuration instead of hand-written bean code. This replaces most manual RestTemplate or WebClient setup for synchronous calls.

Set connect and read timeouts, add retry only for idempotent calls, and propagate trace headers. With virtual threads, blocking RestClient calls are a good default.

Take quiz
What generates the implementation of an @HttpExchange interface?
The Java compiler alone
A JPA provider
Flyway at startup
Spring, on top of RestClient
What should you always configure on outbound HTTP clients?
Connect and read timeouts
A random User-Agent
A larger heap
A Flyway baseline

39. Which is better for persistence: JPA, Spring Data JDBC or jOOQ?

None wins everywhere. Pick by how much of the problem is object mapping and how much is SQL.

Option Strength Watch out for
JPA / Hibernate Rich mapping, fast CRUD, large ecosystem Lazy loading, N+1, dirty-checking surprises
Spring Data JDBC Simple aggregate model, no session or lazy loading Less automatic for complex relations
jOOQ Type-safe SQL, ideal for reporting and complex queries More code; commercial license needed for commercial databases

A common greenfield choice is Spring Data JDBC or JPA for aggregate writes and jOOQ (or plain JdbcClient) for read-heavy queries. If your team knows SQL well and your domain is not deeply object-graph shaped, start simpler than full JPA. Whatever you pick, keep it behind a repository interface so the choice stays local.

Take quiz
Which option gives type-safe SQL, suited to complex reporting queries?
jOOQ
Hibernate lazy loading
Bean Validation
Spring Data JDBC
Which approach avoids lazy loading and a persistence session by design?
Hibernate second-level cache
Spring Data JDBC
JPA with open-in-view
A JPA entity graph

40. How do you prevent the N+1 query problem?

N+1 happens when loading N parent rows triggers one extra query per row to fetch a lazy relation, so a page that should run 1 query runs 101.

  1. Detect it: enable Hibernate statistics or a datasource proxy in tests and assert the query count.
  2. Fetch what you need with join fetch or @EntityGraph.
  3. Batch lazy loads with hibernate.default_batch_fetch_size or @BatchSize.
  4. Project to a DTO and select only the required columns.
  5. Set spring.jpa.open-in-view=false so lazy loading cannot leak into the web layer.
@EntityGraph(attributePaths = "items")
List<Order> findByCustomerId(Long customerId);

Do not fix it by switching every association to EAGER; that moves the cost to every query.

Take quiz
What is a direct fix for N+1 on a known query?
Mark every association EAGER
Use join fetch or an @EntityGraph for the needed relation
Disable the connection pool
Add more application servers
What does spring.jpa.open-in-view=false do?
Turns off Hibernate entirely
Opens a new transaction per HTTP header
Stops lazy loading from happening in the web layer after the service returns
Makes all queries read-only

41. When should you use @Transactional?

Put @Transactional on service-layer methods that represent one business operation, and keep the transaction as short as possible.

  • use readOnly = true for queries; it signals intent and enables some optimizations
  • by default only unchecked exceptions trigger rollback; add rollbackFor for checked ones
  • calling a transactional method from another method in the same class bypasses the proxy, so no transaction applies
  • do not call remote HTTP services inside a transaction; it holds a connection while waiting
  • default propagation is REQUIRED: join the existing transaction or start one
@Service
class TransferService {
    @Transactional(rollbackFor = InsufficientFundsException.class)
    public void transfer(long from, long to, BigDecimal amount) { ... }
}

For side effects outside the database, such as publishing events, combine this with the outbox pattern instead of doing both in the same method.

Take quiz
Which exceptions roll back a @Transactional method by default?
Only SQLException
None, you must always call rollback()
Unchecked exceptions and errors
All checked exceptions
Why might a @Transactional method called from within the same class not start a transaction?
Transactions only work on static methods
The method must be private
The class needs to be a record
The call bypasses the Spring proxy

42. How do you choose a garbage collector in 2026?

Start with the default and change only when measurements show a problem. G1 is the default and a good balance for most services; Java 27 makes it the default even on small machines where earlier JDKs fell back to Serial.

Collector Choose it when Flag
G1 General services, balanced latency and throughput default
ZGC (generational) Large heaps or tight pause targets, sub-millisecond pauses -XX:+UseZGC
Shenandoah (generational) Low pauses, if your JDK build includes it -XX:+UseShenandoahGC
Parallel Batch jobs where only throughput matters -XX:+UseParallelGC
Serial Tiny single-CPU containers or CLI tools -XX:+UseSerialGC

Generational mode for Shenandoah became a product feature in Java 25, and ZGC is generational only since non-generational mode was removed in Java 24. Compare options using GC logs (-Xlog:gc*) and JFR under realistic load, and check p99 latency rather than average.

Take quiz
Which collector is the default in modern JDKs?
ZGC
Epsilon
Parallel
G1
Which collector suits a batch job where only total throughput matters?
Parallel
Shenandoah
Serial on a 64-core host
ZGC

43. How can you optimize startup time with the AOT cache?

The AOT cache (Project Leyden) stores loaded and linked classes plus method profiles from a training run, so later runs skip much of that work. It came with JEP 483 in Java 24, and Java 25 added JEP 514 (simpler command line) and JEP 515 (method profiling).

flowchart LR
  A["Build jar"] --> B["Training run<br/>-XX:AOTCacheOutput=app.aot"]
  B --> C["app.aot file"]
  C --> D["Production run<br/>-XX:AOTCache=app.aot"]
  1. Build the application jar in CI.
  2. Run it once with a representative workload and -XX:AOTCacheOutput=app.aot. For Spring Boot, -Dspring.context.exit=onRefresh ends the training run after startup.
  3. Package app.aot in the image.
  4. Start production with -XX:AOTCache=app.aot.

The cache is tied to the same JDK build and classpath, so generate it at image build time, never ship an old one. Spring Boot's documentation expects Java 25 for this feature.

Take quiz
What must match between the training run and the production run of an AOT cache?
The JDK build and the application classpath
The Git commit author
The garbage collector log path
The operating system hostname
Which flag starts the application using an existing AOT cache?
-Xaot:app.aot
-XX:AOTCache=app.aot
-XX:LoadCache=app.aot
-XX:+UseAOTMode

44. When would you choose GraalVM native image?

Choose a native image when startup time and memory footprint outweigh peak throughput and build convenience: scale-to-zero functions, short-lived CLI tools, or dense deployments with many small instances.

Aspect JVM (with JIT) GraalVM native image
Startup Seconds, less with AOT cache Milliseconds
Memory Higher baseline Much lower
Peak throughput Usually higher after warm-up Often lower without PGO
Build time Fast Slow, memory-hungry
Dynamic features Reflection, proxies work Closed world; needs config or hints
Debugging and tools Full JFR and agents More limited

Spring Boot generates reflection hints through its AOT engine, but every library you add must be native-compatible. Before committing, try the JVM with an AOT cache and compact headers, which often closes enough of the startup gap without giving up JIT or JFR.

Take quiz
Which scenario best fits a GraalVM native image?
Long-running services tuned for maximum JIT throughput
Scale-to-zero functions where startup time dominates
Applications that rely heavily on runtime bytecode generation
Apps that need hot-attach profiling agents
What is a typical drawback of native images?
They require Java 8
They disable all garbage collection
Slow, memory-heavy builds and closed-world limits on reflection
They cannot run Spring Boot

45. Which is better for builds: Maven or Gradle?

Both are production-grade; choose for your team, not for fashion.

Aspect Maven Gradle
Model Declarative XML, strict lifecycle Scripted (Kotlin or Groovy DSL)
Learning curve Gentle and predictable Steeper, very flexible
Speed Good, improved with caching extensions Incremental builds and build cache built in
Large multi-module repos Works, can be slow Usually faster
Readability Verbose but uniform Compact but easy to over-customize

A single service or a handful of modules is often easiest on Maven, since every project looks alike. A big multi-module codebase with custom build logic tends to benefit from Gradle. Spring Boot 4 supports Gradle 9. Whichever you pick: use the wrapper, import the Spring Boot BOM for dependency versions, and keep build logic out of ad hoc scripts.

Take quiz
Which project profile usually suits Maven well?
A project with no dependencies
A project that cannot use a wrapper
A single service with uniform, conventional build needs
A repo needing heavy custom build logic across 200 modules
What should you do regardless of the build tool?
Disable the compiler warnings
Install the tool globally on every CI agent
Commit the local repository cache
Use the wrapper and a BOM for dependency versions

46. How do you structure tests with Testcontainers and slice tests?

Use a pyramid: many fast tests, fewer integrated ones.

  1. Unit tests: plain JUnit, AssertJ and Mockito for domain logic. No Spring.
  2. Slice tests: @WebMvcTest for controllers and @DataJpaTest for repositories, loading only the relevant beans.
  3. Integration tests: a few @SpringBootTest tests with Testcontainers for real PostgreSQL or Kafka, wired by @ServiceConnection.
  4. Contract or end-to-end: a handful that cover the critical user journeys.

Run repository tests against the same database as production rather than H2, and reuse containers across classes to keep the suite quick. In Boot 4, @MockBean is gone; use @MockitoBean. Spring Framework 7 also adds RestTestClient for fluent HTTP tests.

Keep full-context tests few, because each distinct context configuration costs startup time.

Take quiz
Which annotation loads only the web layer for a controller test?
@EnableWebTesting
@SpringBootApplication
@DataJpaTest
@WebMvcTest
Which annotation replaces the removed @MockBean in Spring Boot 4?
@MockitoBean
@MockitoMock
@SpyService
@FakeBean

47. How do you troubleshoot high memory usage in production?

First decide which memory is growing: Java heap, native memory, or just a container limit that is too tight. Then collect evidence.

  1. Check the container limit against -XX:MaxRAMPercentage and look at the OS-level RSS.
  2. Read GC logs (-Xlog:gc*). If old-gen usage never drops after full collections, suspect a heap leak.
  3. Start a JFR recording: jcmd <pid> JFR.start, and look at allocation hot spots and the old-object sample.
  4. Capture a heap dump with jcmd <pid> GC.heap_dump and inspect dominators in Eclipse MAT.
  5. If heap looks fine but RSS grows, run with -XX:NativeMemoryTracking=summary and compare jcmd <pid> VM.native_memory snapshots.

Also set -XX:+HeapDumpOnOutOfMemoryError ahead of time. Common culprits are unbounded caches, listeners never removed, and ThreadLocal data. From Java 27, JFR can redact sensitive environment variables and properties from recordings, which makes sharing them safer.

Take quiz
Which tool captures a heap dump from a running JVM?
jcmd <pid> GC.heap_dump
javac -dump
jcmd <pid> GC.shrink
jar --heap
Heap usage looks normal but container RSS keeps growing. What should you check next?
Spring profile names
Native memory with Native Memory Tracking
The Maven repository size
The Git history

48. Why use the transactional outbox pattern?

It solves the dual-write problem: you cannot atomically update your database and publish a message to a broker. If the app crashes between the two, the data and the event disagree.

With an outbox, the event is inserted into an outbox table in the same local transaction as the business change. A separate relay then publishes it.

sequenceDiagram
  participant S as Service
  participant DB as Database
  participant R as Relay (poller or CDC)
  participant B as Broker
  S->>DB: BEGIN: update order + insert outbox row
  DB-->>S: COMMIT
  R->>DB: read unsent rows
  R->>B: publish event
  R->>DB: mark as sent

The relay can poll the table or use change data capture such as Debezium. Delivery is at-least-once, so consumers must be idempotent, for example by tracking event IDs. Spring Modulith's event publication registry offers a lightweight form of the same idea.

Take quiz
What problem does the transactional outbox pattern address?
Garbage collection pauses
The database update and message publish cannot be done atomically
Slow Maven builds
Missing null checks in controllers
What delivery guarantee does an outbox relay typically give?
Exactly-once with no extra work
No guarantee at all, ever
At-least-once, so consumers must be idempotent
At-most-once

49. How do you secure a new Spring Boot API?

Layer the basics, and let Spring Security 7 do the heavy lifting.

@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(a -> a.requestMatchers("/actuator/health").permitAll()
                                     .anyRequest().authenticated())
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
        .build();
}

  • authenticate with OAuth 2.1 / OIDC JWTs from an identity provider instead of building login yourself; Spring Security 7 uses the lambda DSL only
  • authorize by scope or role, and add @PreAuthorize for fine-grained rules
  • keep CSRF protection on for browser sessions; disable it only for stateless token APIs
  • validate input with Bean Validation and use parameterized queries only
  • hash passwords with the delegating encoder (bcrypt or Argon2), and keep secrets in a manager
  • limit outbound calls to blocklisted internal addresses; Boot 4.1 adds SSRF mitigation for HTTP clients
  • keep dependencies patched and add rate limiting at the gateway

On Java 27, TLS clients negotiate post-quantum hybrid key exchange automatically when the server supports it.

Take quiz
How should a stateless token-based API usually authenticate callers?
Trust an X-User header from any client
Store plain passwords in a cookie
Validate JWTs issued by an identity provider
Rely on obscure URLs
When is it reasonable to disable CSRF protection?
Whenever tests fail
For all admin endpoints
For any API that uses HTTP
For stateless APIs that authenticate with bearer tokens rather than browser cookies

50. How do you manage dependency vulnerabilities and supply chain risk?

Treat third-party code as part of your attack surface and automate the response.

  1. Pin and align versions through the Spring Boot BOM; use Maven Enforcer's dependencyConvergence or Gradle's dependency locking.
  2. Update continuously with Renovate or Dependabot so patches arrive as small pull requests.
  3. Scan every build with OWASP Dependency-Check, OSV-Scanner or Trivy, and fail on high severity findings.
  4. Produce an SBOM (CycloneDX) per build; Spring Boot can also expose it at /actuator/sbom.
  5. Verify artifacts: Gradle dependency verification, a private repository mirror, and signed images (Sigstore cosign).
  6. Use a minimal runtime image and rebuild it regularly to pick up OS patches.

The Log4Shell incident showed the value of knowing exactly which versions you run: with an SBOM you can answer are we affected? in minutes instead of days.

Take quiz
What does an SBOM provide?
A copy of the source code
A faster garbage collector
A list of unit test names
A machine-readable inventory of the components in a build
Which practice delivers dependency patches as small, frequent changes?
Automated update pull requests with Renovate or Dependabot
Disabling the vulnerability scanner
Updating everything once every three years
Copying jars into the repo manually
«
»

Comments & Discussions