Spring Framework Tutorial 0/19 lessons ~6 min read Lesson 19

    Spring 6 AOT & GraalVM Native Images

    Spring normally discovers beans at startup by scanning classes and reading annotations through reflection.

    Course progress0%
    Focus
    11 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Spring normally discovers beans at startup by scanning classes and reading annotations through reflection. Ahead-of-time (AOT) processing, introduced in Spring Framework 6, moves that work to build time: it generates Java source that registers bean definitions directly. GraalVM native image then compiles the application into a standalone executable that starts quickly and uses less memory.

    Native images use a closed-world assumption: everything the app can reach must be known at build time. Reflection, resources, and proxies that Spring cannot infer need runtime hints.

    Purpose of this lesson

    You will understand what AOT generates, what the closed-world assumption forbids, how to register runtime hints and test them, and how to build a native image with the Spring Boot build plugins.

    Understanding the topic

    What changes with AOT:

    • At build time Spring starts the application context in a special mode, then generates source for bean definitions and RuntimeHints instead of running the app.
    • Bean definitions are fixed at build time: @Profile and @Conditional decisions that change the set of beans are evaluated during the build, not at runtime.
    • Reflection, resource loading, serialization, and JDK proxies must be declared in hints if Spring cannot detect them.
    • The JVM can also use AOT-generated code (-Dspring.aot.enabled=true) for faster startup without going native.
    • Native trade-offs: much faster startup and lower memory; slower and heavier builds; no JIT, so peak throughput may be lower than a warmed-up JVM.

    Syntax reference

    Building native images with Spring Boot 3 (requires GraalVM for JDK 17+ with native-image, or Docker for buildpacks):

    bash
    # Maven (spring-boot-starter-parent + native-maven-plugin)
    ./mvnw -Pnative native:compile
    ./target/myapp
    # Maven, container image via Cloud Native Buildpacks (no local GraalVM needed)
    ./mvnw -Pnative spring-boot:build-image
    # Gradle (org.graalvm.buildtools.native plugin)
    ./gradlew nativeCompile
    ./build/native/nativeCompile/myapp
    # JVM with AOT-generated code (no native compilation)
    ./mvnw -Pnative package
    java -Dspring.aot.enabled=true -jar target/myapp.jar

    Production implementation

    Adopting native images safely:

    • Run the test suite against the native image too (./mvnw -PnativeTest test) — JVM tests alone do not prove the hints are complete.
    • Check that every library you use supports native images; many ship hints through the GraalVM reachability metadata repository.
    • Keep profile-specific bean sets out of runtime decisions; use configuration properties for values that change per environment.
    • Measure startup time, memory, and throughput for your own workload before committing — native is a strong fit for scale-to-zero and short-lived workloads, less so for long-running high-throughput services.

    Informative example

    Registering and testing runtime hints for a class read reflectively and for JSON report templates:

    java
    public class ReportRow {
    public ReportRow() {}
    public String getRegion() { return "EU"; }
    }
    public class ReportHints implements RuntimeHintsRegistrar {
    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
    hints.resources().registerPattern("reports/*.json");
    hints.reflection().registerType(ReportRow.class,
    MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
    MemberCategory.INVOKE_PUBLIC_METHODS);
    }
    }
    @Configuration
    @ImportRuntimeHints(ReportHints.class)
    class ReportConfig {}
    public static void main(String[] args) {
    RuntimeHints hints = new RuntimeHints();
    new ReportHints().registerHints(hints, ReportRow.class.getClassLoader());
    System.out.println("reflection on ReportRow: "
    + RuntimeHintsPredicates.reflection().onType(ReportRow.class)
    .withMemberCategory(MemberCategory.INVOKE_PUBLIC_METHODS).test(hints));
    System.out.println("resource reports/daily.json: "
    + RuntimeHintsPredicates.resource().forResource("reports/daily.json").test(hints));
    System.out.println("resource secrets/key.pem: "
    + RuntimeHintsPredicates.resource().forResource("secrets/key.pem").test(hints));
    }

    Output

    reflection on ReportRow: true
    resource reports/daily.json: true
    resource secrets/key.pem: false

    The same RuntimeHintsPredicates checks belong in a unit test, so a missing hint fails the build on the JVM instead of failing at runtime in the native executable. For DTOs serialized by Jackson, @RegisterReflectionForBinding(ReportRow.class) is a shorter alternative.

    Best practices

    • Start with JVM + AOT (spring.aot.enabled) to flush out AOT issues before going native.
    • Prefer constructor injection and explicit configuration — they are the most AOT-friendly patterns.
    • Write RuntimeHintsPredicates tests for every custom RuntimeHintsRegistrar.

    Common mistakes

    • Loading classes by name from configuration (Class.forName(className)) without hints — works on the JVM, fails in the native image.
    • Expecting --spring.profiles.active to switch bean sets at runtime in a native image.
    • Reading classpath resources that were not included by a resource hint.
    • Native builds take minutes and several GB of memory — plan CI runners accordingly.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    2 questions
    1IntermediateQuestionWhat does Spring AOT processing do?+

    Answer

    At build time it evaluates the application context configuration and generates Java source that registers bean definitions directly, plus runtime hints for reflection, resources, serialization, and proxies. This removes much of the startup scanning and makes GraalVM native compilation possible.
    2AdvancedQuestionWhat are the main limitations of Spring native images?+

    Answer

    The closed-world assumption: the set of beans is fixed at build time, so profiles and conditions cannot change it at runtime; reflection, resources, and proxies need hints; builds are slow and memory-hungry; and without a JIT, peak throughput can be lower than a warmed-up JVM.

    Follow-up

    When is native a good fit? (Fast startup and low memory: serverless, CLI tools, scale-to-zero services.)

    Hands-on exercise

    Hands-on: add a second hint for i18n/messages_*.properties and extend the main method to test i18n/messages_fr.properties (expected true). Then remove INVOKE_PUBLIC_METHODS from the registration and predict what the first line prints before running it.

    Summary

    Spring 6 AOT moves context analysis to build time and generates hints; GraalVM turns the result into a fast-starting native executable under a closed-world assumption. Test hints explicitly and measure before adopting native in production.

    Ready to mark this lesson complete?Track your journey across the entire course.