What is a Spring Boot GraalVM native image and what actually changes?

A conventional Spring Boot build produces a jar of bytecode. At runtime the JVM loads classes lazily, Spring scans the classpath, evaluates conditions, creates proxies and wires beans, and the JIT compiler gradually turns hot methods into optimized machine code. Almost every decision is deferred until the application is running.

A GraalVM native image moves those decisions to build time. The native-image tool performs ahead-of-time (AOT) compilation under a closed-world assumption: it starts from the entry point, runs a static analysis to find every reachable class, method and field, and compiles only that code into a standalone, platform-specific executable. Anything the analysis cannot see is absent from the binary. This includes classes loaded by name, reflective calls, dynamic proxies and classpath resources, unless you declare them explicitly. The output contains no bytecode and no JIT. It runs on a minimal runtime (Substrate VM) that provides garbage collection and threading. A binary built on Linux x86-64 runs only on Linux x86-64.

Spring's own AOT step sits between compilation and native-image. During the build, Spring starts the application context in a special mode, evaluates configuration and conditions, and generates Java source for the resulting bean definitions. It also writes reachability metadata (hints for reflection, resources, proxies and serialization) for what the framework knows it will need. The build flow becomes:

compile → Spring AOT processing → native-image analysis and compilation → executable

The jar flow is simply compile → package.

The rest of this article examines the consequences of that extra build-time work.

 JAR BUILD: compile -> package (decisions deferred to runtime)
 +---------+    +---------+    +------------------+    +-------------------+
 | .java   |--->| javac   |--->| package          |--->| app.jar: bytecode |
 +---------+    +---------+    +------------------+    +---------+---------+
                                                                 v
                                   +---------------------------------------+
                                   | JVM at runtime: lazy class loading,   |
                                   | classpath scan, conditions, proxies,  |
                                   | bean wiring, JIT warms up hot methods |
                                   +---------------------------------------+

 NATIVE BUILD: compile -> Spring AOT -> native-image (closed world)
 +---------+    +---------+    +------------------+    +-------------------+
 | .java   |--->| javac   |--->| Spring AOT       |--->| native-image      |
 +---------+    +---------+    | - runs context   |    | - static analysis |
                               |   in AOT mode    |    | - closed world    |
                               | - generates bean |    | - AOT compile     |
                               |   definition src |    |   reachable code  |
                               | - writes hints:  |    | - unseen code and |
                               |   reflection,    |    |   resources absent|
                               |   resources,     |    +---------+---------+
                               |   proxies,       |              |
                               |   serialization  |              |
                               +------------------+              v
                                   +---------------------------------------+
                                   | Platform-specific executable          |
                                   | one OS/arch only (e.g. Linux x86-64)  |
                                   | no bytecode, no JIT                   |
                                   | Substrate VM: GC, threading           |
                                   +---------------------------------------+

A jar build defers class loading, bean wiring and JIT compilation to runtime, while the native build inserts Spring AOT processing and closed-world native-image compilation to produce a platform-specific executable.

How does Spring AOT processing work, and what runtime flexibility do you lose?

Spring AOT runs as a build step after compilation. It starts the application context in a special build-time mode. In this mode it reads bean definitions and evaluates conditions such as @ConditionalOnClass, @ConditionalOnProperty and @Profile, but it does not instantiate the beans. From that analysis it generates Java source that registers the surviving bean definitions directly, without reflection. It also emits hint files that tell native-image which classes need reflection, resources, proxies or serialization. The native compiler then treats that generated code as the complete picture of the application.

That build-time snapshot is where you lose flexibility. The set of beans is decided when you build, not when you start the executable. If a property or active profile at startup is supposed to switch a whole configuration on or off, the native binary ignores that switch. It keeps whatever the build saw. You can still change property values at runtime, such as a URL, a port or a timeout. You cannot change which beans exist. The classpath is also closed. Classes loaded dynamically by name, plugins dropped into a directory, and classpath scanning beyond what AOT already resolved will either fail or need explicit hints.

To enable native builds in Maven:

  • Inherit from spring-boot-starter-parent.
  • Add the GraalVM native-maven-plugin (org.graalvm.buildtools).
  • Build with mvn -Pnative native:compile.

In Gradle:

  • Apply org.graalvm.buildtools.native alongside the Spring Boot plugin.
  • Run ./gradlew nativeCompile.

In both setups the Spring Boot plugin wires AOT processing in automatically.

package com.example.payments;

import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.TypeReference;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;

@Configuration(proxyBeanMethods = false)
@ImportRuntimeHints(PaymentConfig.PluginHints.class)
public class PaymentConfig {

    // Spring AOT evaluates this condition at BUILD time. Whichever bean wins
    // during the AOT run is the only one in the native binary. Passing
    // --payments.provider=stripe to the executable later does not switch it.
    @Bean
    @ConditionalOnProperty(name = "payments.provider", havingValue = "sandbox", matchIfMissing = true)
    PaymentClient sandboxClient(PaymentProperties props) {
        // Property VALUES (URL, timeout) are still read at startup, as on the JVM.
        return new SandboxPaymentClient(props.getBaseUrl(), props.getTimeout());
    }

    @Bean
    @ConditionalOnProperty(name = "payments.provider", havingValue = "stripe")
    PaymentClient stripeClient(PaymentProperties props) {
        return new StripePaymentClient(props.getBaseUrl(), props.getTimeout());
    }

    // A class loaded by name via Class.forName(...) is invisible to the
    // static analysis. Register it explicitly, or the native image fails at runtime.
    static class PluginHints implements RuntimeHintsRegistrar {
        @Override
        public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
            hints.reflection().registerType(
                TypeReference.of("com.example.payments.plugins.FraudCheckPlugin"),
                MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
        }
    }
}

Shows a property-driven conditional bean whose selection is fixed when AOT runs, alongside a RuntimeHintsRegistrar that keeps a class loaded by name reachable in the native image.

Where do startup time and memory gains come from, and when does the JIT win?

Each of the following kinds of startup work happens at build time instead of on every launch:

  • No class loading from JARs. Reachable classes are already compiled into the binary, so nothing is scanned, parsed or loaded from the classpath at startup.
  • No bytecode verification. Verification ran during the build, so the process skips it.
  • No interpreter or JIT warm-up. Code is machine code from the first instruction.
  • Build-time initialization and the image heap. Some objects are created at build time and stored in the binary. Spring AOT has already resolved bean definitions, so the context skips most classpath scanning and reflective inspection.

Memory drops for related reasons. The process has no JIT compiler threads, no profiling counters and no metadata for classes the static analysis found unreachable.

The trade-off is peak performance. A HotSpot JIT compiles hot paths using live profiles, so it can inline, devirtualize and speculate based on how the service actually runs. Ahead-of-time compilation has no runtime profile to work from. On long-running, CPU-bound workloads, a warmed-up JVM can therefore reach higher throughput than a native binary. Profile-guided optimization narrows the gap, but only where your GraalVM distribution supports it, and it adds a step to your build: collecting a profile.

Factor JVM (JIT) Native image
Time to first request Slower Much faster
Idle memory footprint Higher Lower
Peak throughput, long-running Often higher after warm-up Lower unless PGO is used
Performance at first request Interpreted or partly compiled Fully compiled

Faster process startup does not always mean faster readiness. Illustrative estimate (assumed numbers, not a benchmark):

readiness = process start + context init + dependency warm-up

Assume the following, where dependency warm-up covers connection pool setup, migrations and cache warming:

Component (assumed, illustrative) JVM Native
Process start + context init 4 s 0.3 s
Dependency warm-up 8 s 8 s
Readiness 12 s 8.3 s

With these assumed inputs, the illustrative calculation shows a roughly 13× faster process start and context init (4 s vs 0.3 s) producing only about a 30% shorter time to ready (12 s vs 8.3 s). These are not measured results. Your own ratio depends on how long your dependencies take to warm up. If dependency warm-up dominates your readiness time, optimize that before you switch to a native build.

Why does reflection break in native images, and how do you fix reflection config?

native-image builds under a closed-world assumption. At build time it runs a static reachability analysis from your entry points and compiles only the code it can prove is used. Reflection hides that information. A class name passed to Class.forName, a method looked up by string, a JDK dynamic proxy created for an interface, a type deserialized from a byte stream, a Java class accessed from native code through JNI, or a file loaded with getResource: the analyzer cannot see any of these targets. Unless something registers them, they are left out of the image and fail at runtime with errors such as ClassNotFoundException or a missing resource.

Spring's AOT engine generates most of this metadata for beans, configuration classes and proxies it knows about. For anything outside that, such as types reflected by your own code or a library, you implement a RuntimeHintsRegistrar, activate it with @ImportRuntimeHints, and register reflection, resource, proxy, serialization or JNI hints. The GraalVM Reachability Metadata Repository supplies community-maintained metadata for many common libraries, and the Native Build Tools plugins can apply it automatically. To find what is still missing, run your test suite on a JVM with the tracing agent (-agentlib:native-image-agent). It records the dynamic accesses that actually happen. It only sees code paths your tests exercise, so review what it captures before you commit it.

Expect ongoing maintenance. Hints can drift as you refactor your code and upgrade Spring, GraalVM or libraries. A library with no published metadata and heavy reflection is a real adoption risk. The only reliable check is to run your tests against the native binary in CI.

package com.example.orders;

import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.TypeReference;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;

// Activates the registrar only when this configuration is part of the context.
@Configuration(proxyBeanMethods = false)
@ImportRuntimeHints(OrdersConfig.OrdersHints.class)
public class OrdersConfig {

    static class OrdersHints implements RuntimeHintsRegistrar {
        @Override
        public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
            // A plugin class loaded by name with Class.forName(): the analyzer cannot see it.
            hints.reflection().registerType(
                    TypeReference.of("com.example.orders.plugins.DefaultPricingPlugin"),
                    MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
                    MemberCategory.INVOKE_PUBLIC_METHODS);

            // Files read with getResource()/getResourceAsStream() must be embedded in the image.
            hints.resources().registerPattern("pricing/*.json");

            // A JDK dynamic proxy created at runtime for this interface.
            hints.proxies().registerJdkProxy(AuditListener.class);

            // A type read back with ObjectInputStream from a cache or queue.
            hints.serialization().registerType(OrderSnapshot.class);
        }
    }

    public interface AuditListener { void onEvent(String event); }

    public record OrderSnapshot(String orderId, long totalCents) implements java.io.Serializable { }
}

A Spring RuntimeHintsRegistrar, activated with @ImportRuntimeHints, that registers reflection, resource, JDK proxy and serialization hints for dynamic accesses the native-image static analysis cannot detect on its own.

When should you use a native image, and when should you avoid it?

The deciding question is whether your workload pays for JVM warm-up repeatedly or only once. A native image front-loads optimization into the build, so it helps most when processes are short-lived, frequently started, or packed tightly onto shared hardware.

Workload Recommendation Why
Scale-to-zero services, serverless functions Native Every cold start is user-facing latency, and you are billed for memory per instance
CLI tools, short batch jobs Native The process exits before the JIT would finish optimizing hot paths
Dense multi-tenant clusters Native A lower resident memory footprint per pod lets more replicas fit per node
Long-lived, high-throughput services with large heaps JVM Profile-guided JIT optimization and mature garbage collectors pay off over hours of uptime
Services with steady traffic and rare restarts JVM Startup cost is amortized, so faster boot buys little

The teams most likely to benefit already have strong test coverage, a fairly conventional Spring stack, and CI capacity to absorb longer builds. Coverage matters because a missing reflection hint shows up only on the code path that triggers it.

Be cautious if you see these warning signs:

  • Heavy reflection or dynamic proxy libraries without published reachability metadata. You will end up maintaining their hints yourself.
  • Reliance on Java agents for APM, profiling or bytecode instrumentation. Agents that attach at runtime have no equivalent in a closed-world binary.
  • Frequent runtime configuration changes that toggle beans, profiles or conditional wiring. AOT fixes these decisions at build time, so any change means a rebuild instead of a restart.

What are the alternatives to GraalVM native images for faster JVM startup?

Before accepting a closed-world binary, check whether a standard JVM can get close enough. Each of the options below keeps the JIT and leaves your dynamic behaviour intact.

Class data sharing (CDS/AppCDS) stores parsed and verified class metadata in an archive that the JVM memory-maps at startup. A large share of Spring Boot startup goes to loading and verifying thousands of classes, so skipping that work helps. The archive is only valid for the JDK build and classpath that produced it. You therefore generate it in the same pipeline step that builds the image. The application code is unchanged, and agents and profilers still work.

Checkpoint/restore (for example, OpenJDK's CRaC) snapshots a running, warmed JVM and restores it later. Restoring skips both startup and warmup, because already-compiled code is in the snapshot. The costs are operational:

  • It depends on Linux-specific tooling.
  • Open sockets and file handles must be closed before the checkpoint and reopened after restore.
  • Any secrets or environment state in memory at checkpoint time are baked into the image.

Plain JVM tuning costs the least to try:

  • Lazy bean initialization defers work until a bean is first used.
  • Limiting tiered compilation reduces early JIT overhead.
  • Right-sized heaps and trimmed auto-configuration remove unneeded startup work.

These steps trade some peak throughput or first-request latency for a faster start.

Option Startup improvement JIT peak performance Tooling and agent compatibility Build/ops complexity
CDS/AppCDS Moderate Fully retained Full Low: archive tied to JDK and classpath
Checkpoint/restore Large, includes warmup Retained from snapshot Partial: resources must handle checkpoint High: platform constraints, snapshot hygiene
JVM tuning Small to moderate Retained or slightly reduced Full Very low
Native image Largest No JIT; relies on AOT-compiled code Limited High: reflection config, long builds

How do native builds affect CI, testing and development cost?

Native compilation is the slowest and most resource-intensive step in the pipeline. A jar build compiles your classes and packages them. native-image does far more: it runs a whole-program, closed-world analysis over your code, every dependency and the JDK classes you reach, and only then compiles the result ahead of time. That analysis is why builds take minutes instead of seconds and why they need several gigabytes of RAM. Undersized shared CI runners often fail with out-of-memory errors rather than compile errors, so size the build agents explicitly.

The output is a platform binary, not portable bytecode. A Linux x86-64 executable will not run on ARM64, and native-image does not cross-compile. A multi-arch container image therefore needs one build per architecture on a matching runner (or under emulation, which is much slower), followed by a step that merges the results into a manifest list. Most teams run the build inside a container, either through Buildpacks (./mvnw -Pnative spring-boot:build-image or ./gradlew bootBuildImage) or a GraalVM builder image, so that local and CI toolchains match.

Keep the inner loop on the JVM. Unit tests, bootRun and hot reload should stay fast. Run native builds and native-mode tests in CI, because many failures appear only in the compiled binary. Examples include a missing reflection or resource hint, or a @Conditional that resolved differently at build time. To run the test suite as a native executable, use ./mvnw -PnativeTest test with Maven or ./gradlew nativeTest with the GraalVM Native Build Tools plugin. Run this at least on main-branch merges, and ideally on every pull request that changes dependencies or configuration.

#!/usr/bin/env bash
set -euo pipefail

./mvnw test                      # fast unit/integration tests on the JVM
./mvnw spring-boot:run           # run the app with normal JVM startup

./mvnw -PnativeTest test

ARCH="$(uname -m)"               # e.g. x86_64 or aarch64
IMAGE="registry.example.com/orders-service"
TAG="1.4.0"

./mvnw -Pnative spring-boot:build-image \
  -Dspring-boot.build-image.imageName="${IMAGE}:${TAG}-${ARCH}"
docker push "${IMAGE}:${TAG}-${ARCH}"

A pipeline script that keeps JVM-mode tests on the developer machine, runs native-mode tests and per-architecture Buildpacks builds in CI, and merges the per-architecture images into a multi-arch manifest list.

Does a native image save money? An illustrative cost estimate and operational trade-offs

Runtime savings come from lower memory per instance and, for bursty or scale-to-zero workloads, from shorter cold starts. Weigh them against build and engineering costs with one formula:

Monthly net = (instances × (JVM GiB − native GiB) × price per GiB-month) − (extra CI minutes per build × builds per month × price per CI minute) − (engineering hours × hourly cost ÷ months amortized)

Illustrative estimate (assumed numbers, not a benchmark): 20 instances using 0.5 GiB on the JVM vs 0.2 GiB native, at $4 per GiB-month, gives 20 × 0.3 × 4 = $24 saved. Native builds add 8 minutes each, for 300 builds a month at $0.01 per minute, which is $24 spent. The net is zero before you count a single engineering hour. The memory term only wins on large fleets. The startup term matters when instances start frequently.

Concern JVM mode Native image
Java-agent APM Attach agent at startup Generally not applicable
Heap dumps, JFR-style profiling Mature, standard tooling Reduced or different support
Stack traces and behavior Reference behavior May differ; reflection gaps show up at runtime
Incident triage Familiar runbooks Needs separate runbooks

These gaps cost time during incidents, which is when it is most expensive. An on-call engineer who loses their usual profiler or agent-based traces has to diagnose with less information. A failure that appears only in native mode also has to be reproduced in a native build, and each native build is slow.

To limit the effort, scope native images to the workloads where startup time or memory density pays for itself, such as functions, CLIs and scale-to-zero services. Keep long-running, high-throughput services on the JVM. Revisit the formula when fleet size or traffic patterns change.

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.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

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.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • 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.