What is a Spring Boot GraalVM native image and how does the closed-world model work?
A native image is a standalone executable that GraalVM's native-image tool compiles ahead of time from your application and its dependencies. It contains your compiled code, the parts of the JDK you use, a minimal runtime, and a pre-initialized heap. No JVM loads bytecode at startup.
The build follows a closed-world assumption. native-image runs static reachability analysis from the entry point and keeps only the classes, methods and fields it can prove are reachable. Everything else is dropped, and classes cannot be loaded dynamically at runtime. Static analysis cannot see targets that are chosen only at runtime. Code reached through reflection, classpath resources, JDK dynamic proxies or serialization must be declared in advance. If it is not declared, it is missing from the binary, and you get a failure at runtime instead of at build time.
Spring AOT processing closes this gap. At build time it starts the application context far enough to evaluate bean definitions, without instantiating the beans. It then generates Java source that registers those beans directly, which removes classpath scanning and configuration parsing at startup. It also emits reflection, resource, proxy and serialization hints for native-image to consume.
AOT resolves conditions such as @Profile and @ConditionalOnProperty during the build. The bean graph is therefore fixed. Changing a profile or property at runtime will not add or remove beans.
Native:
sources ─► Spring AOT processing ─► native-image ─────────────► executable
├ bean registration code ├ reachability analysis
└ reflection/resource/ └ image heap snapshot
proxy/serialization hints
JVM:
jar ─► classpath scanning ─► bean-definition parsing ─► interpretation + JIT
NATIVE PATH (build time does the work)
┌──────────────┐ ┌───────────────────────────┐ ┌─────────────────────┐
│ Sources │──►│ Spring AOT processing │──►│ native-image │
│ app + deps │ │ evaluate bean definitions │ │ reachability │
└──────────────┘ │ resolve @Profile and │ │ analysis (closed │
│ @ConditionalOnProperty │ │ world) │
├───────────────────────────┤ │ image heap snapshot │
│ generated bean │ └──────────┬──────────┘
│ registration code │ │
│ reflection / resource / │ ▼
│ proxy / serialization │ ┌─────────────────────┐
│ hints │ │ native executable │
└───────────────────────────┘ │ no classpath scan │
│ fixed bean graph │
└─────────────────────┘
JVM PATH (this work happens at every startup)
┌─────┐ ┌───────────┐ ┌─────────────────┐ ┌─────────────┐
│ jar │──►│ classpath │──►│ bean-definition │──►│ interpreter │
│ │ │ scanning │ │ parsing │ │ + JIT │
└─────┘ └───────────┘ └─────────────────┘ └─────────────┘
On the native path, Spring AOT fixes the bean graph and emits hints so native-image can run closed-world reachability analysis and snapshot the heap at build time, while the JVM path scans the classpath, parses bean definitions and JIT-compiles at every startup.
Why does native startup time improve, and what does it not improve?
The gains come from moving work out of the process's startup path and into the build. On the JVM, every launch repeats the same steps: load and verify classes, interpret bytecode until hot methods are JIT-compiled, scan the classpath for components, and parse configuration into bean definitions. A native image does these once at build time and ships the result.
| JVM phase | In a native image | Metric affected |
|---|---|---|
| Class loading and verification | Done at build time; no class loader at runtime | Startup time |
| Interpretation and JIT warmup | Code is already machine code | Time to first fast request |
| Classpath scanning | Replaced by generated bean registration code | Startup time |
| Bean-definition parsing | Precomputed by AOT processing | Startup time, memory |
| Static initialization | Partly captured in the image heap snapshot | Startup time |
| JIT compiler threads and metadata | Absent | Resident memory |
None of this raises peak throughput. A warmed-up JIT compiles against the profile of live traffic: it inlines the call sites that are actually hot, specializes on observed types, and deoptimizes when those assumptions break. An AOT compiler must stay correct for every path it cannot rule out, so it makes more conservative choices. On a long-running service with steady load, the binary can settle below the throughput of a warmed JVM. Profile-guided optimization narrows this gap, but it requires an extra build-and-profile step and is not available in every GraalVM distribution.
Garbage collection also changes. Native images do not offer the full set of HotSpot collectors. The default collector is simpler, and lower-pause options such as G1 are limited to particular distributions and platforms. Benchmark GC behaviour under your real heap size instead of assuming it matches HotSpot.
Who should use Spring Native, and when should you avoid it?
The strongest case is any workload where startup and idle memory dominate cost. Scale-to-zero services pay startup on every cold request. CLI tools and short-lived batch jobs finish before a JIT would warm up. Memory-dense deployments pack more instances per node because there is no JIT compiler or class metadata loaded at runtime.
The case is weak for services that start once and run for days. There, startup is amortised to nothing, and a warmed JIT usually reaches higher peak throughput than ahead-of-time compiled code. AOT processing also fixes the bean graph at build time. Profile-specific beans and @ConditionalOnProperty decisions are evaluated during the build, so switching profiles at runtime does not add or remove beans. Keep one bean graph and inject differing values (URLs, credentials, timeouts) through environment variables or mounted config. If environments need structurally different beans, build separate images.
Operationally, expect gaps:
- APM agents:
-javaagentagents generally cannot attach. - Diagnostics: heap dumps, JFR and debugger support are reduced or work differently.
- Platform: each binary targets one OS and CPU architecture, so multi-arch fleets need one build per target.
| Workload trait | Fit | Reason |
|---|---|---|
| Scale-to-zero / frequent cold starts | Good | Startup cost is paid on every scale-up |
| CLI or short-lived job | Good | Exits before a JIT would warm up |
| High instance density | Good | Lower baseline memory per instance |
| Profiles chosen at deploy time | Conditional | Works if the bean graph is fixed; use runtime values or separate images |
| Long-running, throughput-bound | Poor | Warmed JIT usually wins on peak throughput |
| Libraries using runtime bytecode generation, proxies or agents | Poor | Breaks the closed-world assumption |
How do you write AOT reflection hints in Spring Boot?
The AOT engine already handles Spring's own beans, configuration classes and @Controller method signatures. Hints are for what it cannot see statically. That includes a library calling Class.forName with a name read from config, a reflection-based mapper instantiating types it discovers at runtime, a resource path built by string concatenation, a JDK dynamic proxy created outside Spring's proxy infrastructure, and Java serialization.
Registering hints programmatically
Implement RuntimeHintsRegistrar and override registerHints(RuntimeHints hints, ClassLoader classLoader). Inside it, there are four registries:
hints.reflection().registerType(...)takes the target class and theMemberCategoryvalues you need, such asINVOKE_DECLARED_CONSTRUCTORSorDECLARED_FIELDS. Request only those categories, because each one keeps more metadata in the image.hints.resources().registerPattern("templates/*.json")includes files that are looked up by computed names.hints.proxies().registerJdkProxy(...)takes the interfaces in the same order the proxy is created with.hints.serialization().registerType(...)covers classes that pass throughObjectInputStream.
Activate the registrar by putting @ImportRuntimeHints(MyHints.class) on a @Configuration class. This keeps each hint next to the code that needs it.
Jackson DTOs
When a DTO is serialized manually, for example with objectMapper.writeValueAsString on a type that never appears in a controller signature, add @RegisterReflectionForBinding(OrderDto.class) to a bean or configuration class. It registers the constructors, fields and accessors that Jackson uses.
Why missing hints are dangerous
The failures only show up on code paths that run in the native binary:
- A missing reflection hint throws
ClassNotFoundException. - A missing resource hint returns
nullfromgetResource. - A missing binding hint is the worst case. Jackson finds no accessors and writes
{}or omits fields, with no exception.
Tests on the JVM pass in all three cases. The defect surfaces in production, on the first request that takes that path.
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;
// Activates the registrar and registers Jackson binding hints for a DTO
// that is only serialized manually via objectMapper.writeValueAsString.
@Configuration
@ImportRuntimeHints(PaymentHints.class)
@RegisterReflectionForBinding(OrderDto.class)
class PaymentConfig {
}
class PaymentHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
// Loaded by a library via Class.forName(name from config) and instantiated.
// Request only the categories that the library actually uses.
hints.reflection().registerType(StripeLikeGateway.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
// Files looked up by computed names such as "templates/" + region + ".json".
hints.resources().registerPattern("templates/*.json");
// JDK proxy created with Proxy.newProxyInstance outside Spring.
// List the interfaces in the same order used at creation time.
hints.proxies().registerJdkProxy(PricingClient.class, AutoCloseable.class);
// Class that is read back through ObjectInputStream.
hints.serialization().registerType(CachedQuote.class);
}
}
A RuntimeHintsRegistrar that registers reflection, a resource pattern, a JDK proxy and serialization hints, activated with @ImportRuntimeHints, plus @RegisterReflectionForBinding for a Jackson DTO.
How do you find missing reachability metadata with the tracing agent?
The fix for that class of bug is to stop guessing. GraalVM ships a tracing agent that runs inside an ordinary JVM, watches every reflective lookup, resource load, proxy creation and serialization call, and writes what it observed as JSON reachability metadata. Attach it with -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image/com.example/orders. The build picks up metadata from that location automatically, so the output lands where it will be used. To accumulate results across several runs, use config-merge-dir instead, which adds to existing files rather than overwriting them.
The agent records only what actually executes. A Jackson DTO that is serialized only on an error path, or a JDBC driver class loaded only when a connection fails over, will be missing unless your traffic triggers it. Drive the agent with integration tests and realistic request replays, not a smoke test that hits /health. Coverage is only as good as that traffic.
Review the output before you commit it. The agent records everything, including classes touched by test frameworks, mocking libraries and IDE tooling. Committing all of it hides which entries matter. It also keeps classes in the image that do not need to be there. Delete entries that belong to test infrastructure, and turn the rest into explicit RuntimeHints where that makes the intent clearer.
For third-party libraries, check the community-maintained GraalVM Reachability Metadata repository first. The Spring Boot build plugins can consume it, and its entries are tested against specific library versions.
Anything you write by hand is pinned to the dependency versions you traced. A library upgrade can rename an internal class or add a new reflective path without failing your JVM tests. Re-run the agent and the native test suite on every upgrade.
#!/usr/bin/env bash
# Trace a Spring Boot app on a GraalVM JDK to generate reachability metadata.
# Re-run this after every dependency upgrade, then review the diff.
set -euo pipefail
OUT=src/main/resources/META-INF/native-image/com.example/orders
JAR=target/orders-0.0.1-SNAPSHOT.jar
./mvnw -q -DskipTests package
# Run 1: start fresh. config-output-dir overwrites existing files.
java -agentlib:native-image-agent=config-output-dir="$OUT" -jar "$JAR" &
APP_PID=$!
sleep 15 # crude wait for startup; poll a readiness endpoint in real scripts
# Exercise real code paths, including error paths, not just /health.
curl -s -X POST localhost:8080/orders -H 'Content-Type: application/json' \
-d '{"sku":"ABC-123","quantity":2}' > /dev/null
curl -s localhost:8080/orders/does-not-exist > /dev/null # 404 / error DTO
curl -s -X POST localhost:8080/orders -H 'Content-Type: application/json' \
-d '{"sku":""}' > /dev/null # validation failure
# The agent writes its files when the JVM exits; SIGTERM allows a clean shutdown.
kill -TERM "$APP_PID"; wait "$APP_PID" || true
# Run 2: add what the integration test suite touches.
# config-merge-dir adds to the existing files instead of replacing them.
# (Assumes tests run in a forked JVM that honors argLine.)
./mvnw -q verify \
-DargLine="-agentlib:native-image-agent=config-merge-dir=$OUT"
# Review before committing: drop entries from test frameworks, mocking
# libraries and tooling, and move intentional ones into RuntimeHints.
ls "$OUT"
git diff --stat -- "$OUT"
Runs the app and its integration tests on the JVM with the GraalVM tracing agent, using config-output-dir for a fresh trace and config-merge-dir to add to it, then lists and diffs the generated metadata for manual review.
How do you build and test a native image in CI?
Spring Boot gives you two paths. With the GraalVM Native Build Tools plugin, Maven builds a local executable via mvn -Pnative native:compile, and Gradle via ./gradlew nativeCompile. These require a GraalVM toolchain on the build machine. Alternatively, mvn -Pnative spring-boot:build-image or ./gradlew bootBuildImage produces a container image through Cloud Native Buildpacks. The builder image supplies the compiler, so CI agents only need a container runtime.
Run the tests natively
Passing JVM tests prove your logic, not your binary. A missing hint, a serializer that silently drops a field, or a proxy that was never generated only appears once the code runs inside the closed world. Run mvn -PnativeTest test or ./gradlew nativeTest to compile the test suite itself into a native executable and run it.
Build-time versus run-time initialization
Classes initialized at build time have their static state captured in the image heap. A static final timestamp becomes the build date. A seeded Random produces the same sequence on every start. A value read from an environment variable reflects the CI runner, not production. The failure modes differ by phase:
- Wrong phase at build time: the build aborts because an object such as a thread or an open file descriptor ended up in the image heap.
- Moved to run time without its dependencies: the build succeeds, but the application fails on its first call.
CI implications
- Build time and memory: native builds take minutes rather than seconds and need several gigabytes of builder memory. Give them dedicated runners.
- One build per architecture: a binary targets a single OS and CPU architecture, so you need one build per target, for example amd64 and arm64.
- Different artifacts in dev and prod: developers iterate on the JVM, so the artifact they debug is not the one you ship. A scheduled or pre-merge native test job is the only way to close that gap.
#!/usr/bin/env bash
# CI job for a Spring Boot native image (Maven).
# Assumes a GraalVM JDK on the runner and the spring-boot-starter-parent
# 'native' and 'nativeTest' profiles. Run once per target architecture.
set -euo pipefail
echo "Building for $(uname -s)/$(uname -m)"
# 1. Fast feedback: the normal JVM test suite checks application logic.
./mvnw -B test
# 2. Compile the tests into a native executable and run it. This catches
# missing reflection/proxy/resource hints and code that was initialized
# in the wrong phase, none of which show up on the JVM.
./mvnw -B -PnativeTest test
# 3. Build the native executable. Tests already ran above, so skip them here.
./mvnw -B -Pnative -DskipTests native:compile
# 4. Smoke-test the binary that will actually ship.
# 'demo-app' is a placeholder for the artifactId.
./target/demo-app --server.port=0 &
APP_PID=$!
sleep 5
kill -0 "$APP_PID" # fails the job if the process already exited at startup
kill "$APP_PID"
# Alternative to step 3 when the runner has no GraalVM, only a container runtime.
# The buildpack builder image supplies the native compiler:
# ./mvnw -B -Pnative -DskipTests spring-boot:build-image
# Gradle equivalents:
# ./gradlew test
# ./gradlew nativeTest
# ./gradlew nativeCompile # executable in build/native/nativeCompile/
# ./gradlew bootBuildImage
A CI script that runs the JVM tests, runs the same suite as a native executable, builds the native binary and smoke-tests it, and lists the buildpack and Gradle alternatives.
How should you evaluate native images against alternatives like CDS and checkpoint/restore?
Run both builds of the same service in the target environment, with the same container limits, the same orchestrator and production-like traffic. Record five numbers per build: time to first successful request (from process start to a 200, not "started" in the log), resident memory under steady load, p99 latency after warmup, sustained throughput and CI build time. Laptop results do not transfer, because CPU quotas and memory limits change both JIT behavior and native heap sizing.
Illustrative estimate. These inputs are assumed. A scale-to-zero service has 20,000 cold starts a month. The JVM build needs 1 GB and takes 5 s to serve its first request. The native build needs 256 MB and takes 0.3 s. Billed cold-start cost is 20,000 × 5 s × 1 GB = 100,000 GB-s for the JVM, against 20,000 × 0.3 s × 0.25 GB = 1,500 GB-s for native. The latency cost may matter more than the billing cost: each of those 20,000 requests waits 5 s instead of 0.3 s.
| Option | Startup | Peak performance | Compatibility | Tooling | Development cost |
|---|---|---|---|---|---|
| Native image | Fastest | Often below JIT | Closed world; needs hints | Native debuggers, slower builds | Hints plus native CI |
| CDS | Moderate gain | Full JIT | Near-total | Standard JVM | Low; archive per build |
| Checkpoint/restore | Very fast restore | Full JIT, warmed | Must close and reopen sockets and secrets | Runtime and OS support required | Lifecycle handling |
| Tuned JVM | Slowest | Full JIT | Total | Standard JVM | Lowest |
Count what native removes: cold-start workarounds such as warm pools or minimum replicas, and memory per instance multiplied by replica count. Then count what it adds: hint maintenance on every library upgrade, native CI minutes and runbook changes, because thread dumps, heap analysis and JFR-based profiling either work differently or do not work at all. If CDS or checkpoint/restore closes most of the startup gap, they are usually cheaper to adopt.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to spring boot graalvm native image, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.