Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 66 ยท Packaging and Deployment

Native Images with GraalVM

Compile a Spring Boot app to a native executable with GraalVM: AOT processing, runtime hints, build time versus startup, limits and when it pays off.

A normal Spring Boot application starts a JVM, loads thousands of classes, scans for beans, evaluates conditions and only then serves its first request. That takes a few seconds and a few hundred megabytes. A native image moves most of that work to build time. GraalVM compiles your application ahead of time into a standalone executable that starts in tens of milliseconds and uses much less memory, with no JVM inside.

Native images are powerful, but they change how your program behaves and how you build it. This lesson explains what Spring does at build time (AOT processing), why reflection needs hints, what you give up, and how to decide whether it is worth it. The Java-level background is in GraalVM Native Image; for the plain jar route see Building and Running the Jar.

GraalVM, Maven and Gradle cannot run here, so the commands and Spring code are read-only. The two runnable examples are stand-ins that model the key ideas: a reachability analysis and a reflection allow-list.

What happens at build time

On a normal JVM, Spring discovers your application while it starts: it scans classes, reads annotations, evaluates @ConditionalOn... rules and builds bean definitions through reflection. A native image cannot do that freely, so Spring Boot first runs AOT (ahead-of-time) processing during the build:

What AOT processing does

Scan Finds your beans and configuration classes.
Decide Evaluates conditions and profiles once, now.
Generate Writes plain Java that creates every bean.
Record hints Lists what needs reflection or resources.

Startup no longer has to discover anything.

1 / 2

The generated code is ordinary Java source (you can find it under target/spring-aot/main/sources), and the hints go into JSON files that GraalVM reads. Then the native-image compiler takes over:

flowchart LR
    A["Your code<br/>and libraries"] --> B["Spring AOT<br/>(generated beans + hints)"]
    B --> C["native-image<br/>(closed-world analysis)"]
    C --> D["Executable<br/>(no JVM needed)"]

From source to a standalone binary: Spring prepares the code, GraalVM analyzes and compiles it.

Building one

Spring Boot's build plugins make this a single command:

Terminal
# Maven: native executable on your machine (needs a GraalVM JDK)
./mvnw -Pnative native:compile

# Maven: native container image with buildpacks (needs Docker only)
./mvnw -Pnative spring-boot:build-image

# Gradle (with the org.graalvm.buildtools.native plugin applied)
./gradlew nativeCompile
./gradlew bootBuildImage

# run your tests as a native image too
./mvnw -PnativeTest test
./gradlew nativeTest

The native profile comes with spring-boot-starter-parent. To test AOT-processed code on a normal JVM first, which is fast and catches many mistakes, run the AOT step and start the jar with -Dspring.aot.enabled=true. The build-image variant needs no local GraalVM installation, only Docker, which is why many teams build native images in CI containers. For the container side see Containers: Dockerfile and Buildpacks.

The closed-world assumption

native-image performs a closed-world analysis: starting from main, it follows every call it can see and includes only the classes and methods that are reachable. Everything else is dropped, which is why the executable is small and starts fast. The price is that anything the analysis cannot see is missing at runtime.

This stand-in runs the same idea over a small call graph. It starts at the entry point, follows calls, and reports what would stay in the image. A class that is only looked up by name from configuration is not reachable, until a hint adds it as an extra root.

Java Reachability analysis: what stays in the image

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Dead code such as ReportService.monthly disappears, which is the point. CsvExporter.export also disappears in the first run, which is the trap: the code that loads it by name is invisible to the analysis.

Runtime hints for reflection, resources and proxies

Spring registers hints for its own machinery and for most popular libraries. For your own dynamic features you add hints. The usual cases are reflection on a class, a resource file loaded by path, a JDK dynamic proxy and a type serialized by a library such as Jackson:

Java
@Configuration
@ImportRuntimeHints(ExportHints.class)
class ExportConfig {
}

class ExportHints implements RuntimeHintsRegistrar {

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
        hints.reflection().registerType(CsvExporter.class,
            MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
        hints.resources().registerPattern("templates/*.txt");
        hints.proxies().registerJdkProxy(Exporter.class);
    }
}

For JSON binding there is a shortcut annotation:

Java
@RegisterReflectionForBinding({OrderRequest.class, OrderResponse.class})
@RestController
class OrderController { /* ... */ }

When a class that Spring cannot see is missing a hint, the native program fails at runtime, not at build time. That is why native tests (nativeTest) matter, and why you should run the full test suite on the native binary in CI. The GraalVM build tools can also download community-maintained metadata for popular libraries, and a tracing agent can record what a JVM run actually used, which helps when a library has no metadata yet.

This second stand-in models the runtime failure. A small "closed world" object only creates classes that were registered, like a native image does, and fails for others.

Java A reflection allow-list, like a native image

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The real error text differs (GraalVM reports missing reflection registrations in its own words), but the lesson is the same: the failure shows up when that code path runs, so test every path.

What you give up

  • Dynamic features. Reflection, JDK proxies, resources, serialization and JNI need hints. Loading classes at runtime from outside the image (plugins, agents) does not work.
  • Decisions made at build time. Profiles and @ConditionalOn... conditions are evaluated during AOT processing, so a different profile or property that changes which beans exist needs a different build. Ordinary property values can still change at runtime.
  • JVM tooling. Java agents and many JVM diagnostics do not apply to a native executable. Monitoring still works through Actuator and logs.
  • Build time and resources. A native build takes minutes and several gigabytes of RAM, with no incremental mode. Developers usually work on the JVM and build native in CI.
  • Peak throughput and GC choices. A JVM with JIT compilation can keep optimizing a long-running service using what it learns at runtime. A native image has no warm-up, but its steady-state speed is often equal or lower, and it offers fewer garbage collectors.

When it pays off

Workload Native image?
Serverless functions, scale-to-zero services Yes: start-up time is the cost you pay on every cold start
Command-line tools and short jobs Yes: no JVM warm-up
Many small instances on limited memory Often yes: lower memory per instance
Long-running service with heavy, steady load Usually no: the JVM's JIT catches up and wins on throughput
Code using many reflection-heavy libraries without metadata Probably not: the hint work outweighs the gain

Before you commit, try the cheaper options: trimming dependencies, lazy initialization, class-data sharing or an AOT cache for faster JVM startup, and the tuning ideas in Performance Tuning. Measure start-up, memory and throughput on your own application first, because the numbers depend on it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Spring's AOT processing do during the build?

    AOT processing replaces start-up discovery with generated code and hint files. The machine-code compilation is the separate native-image step that follows.
  2. 2. Why can a class that is created only through Class.forName(name) be missing in a native image?

    The analysis follows calls it can see. A class name that is only known at runtime is invisible to it, so you must register the class with a runtime hint.
  3. 3. Which workload benefits most from a native image?

    Start-up time and memory are the native image's strengths. Dynamic class loading and runtime bean changes are weak spots, and heavy steady load often favors the JIT.
  4. 4. Why should you run your test suite on the native binary, for example with nativeTest?

    A missing reflection or resource hint only shows up when the code that needs it executes, so tests on the native binary are the safety net.

Summary

  • A native image is an ahead-of-time compiled executable: fast start, low memory, no JVM, but a slow, memory-hungry build.
  • Spring AOT processing evaluates conditions at build time and generates bean-creation code and runtime hints.
  • GraalVM uses a closed-world analysis: anything reached only through reflection, proxies, resources or serialization needs a hint (RuntimeHintsRegistrar, @ImportRuntimeHints, @RegisterReflectionForBinding).
  • Profiles and conditions are fixed at build time; plugins and runtime class loading do not work.
  • Test on the native binary, build natively in CI, and develop on the JVM.
  • Choose native for serverless, CLIs and many small instances; stay on the JVM for long-running high-throughput services.

Next: Deployment: Cloud, Kubernetes and Config.