Spring Boot native images: what AOT does before GraalVM

A GraalVM native image starts in milliseconds, but only works if Spring can describe the whole application at build time. This page runs Spring's AOT processing on a normal JVM, shows the code and hints it generates, demonstrates the conditions it freezes, and explains how to supply the hints it cannot infer.

Contents

What a native image is, and why Spring needs AOT for it

A normal Spring Boot application starts on the JVM: classes load lazily, the JIT compiler turns hot code into machine code while it runs, and Spring builds its beans by reading annotations with reflection. That flexibility costs startup time and memory, which matters for serverless functions, command-line tools and services that scale from zero.

GraalVM Native Image compiles the application ahead of time into a single executable. At build time it starts from main, follows every reachable call, and compiles only what it finds. The result starts in a fraction of a second and uses less memory, but it lives in a closed world:

  • Only reachable code exists: code the analysis cannot see is not in the executable.
  • Dynamic features need hints: reflection, resources, dynamic proxies and JNI work only for the types and files declared at build time.
  • The classpath is fixed: nothing can be added or loaded later.

Spring's usual startup is the opposite of a closed world: it scans the classpath, evaluates conditions, and creates beans through reflection. Spring's AOT engine closes that gap. At build time it starts the application context far enough to know every bean definition, then writes Java code that registers those beans directly, plus the hint files GraalVM needs. The native executable runs that generated code instead of scanning.

JVM, AOT on the JVM and native image compared
AspectPlain JVMAOT on the JVMNative image
Bean definitionsComputed at startupGenerated at build timeGenerated at build time
Conditions and profilesEvaluated at startupFixed at build timeFixed at build time
Startup workScanning, parsing and condition evaluationSkips configuration parsingSkips that and class loading and JIT warm-up as well
Peak throughputBest, after JIT warm-upSame as JVMOften lower without profile-guided optimisation
Build timeFastSlightly longerMinutes, and several GB of memory
Reflection and dynamic proxiesUnrestrictedUnrestrictedOnly with hints

No GraalVM is installed where this page was built, so no native executable was compiled or run here. Everything the AOT engine does before GraalVM takes over runs on a normal JVM, and the programs below run it with Spring Boot 4.1.2 and Spring Framework 7.0.10 on Java 21. The build commands in the later section are taken from the Spring Boot reference documentation and were not run.

AOT processing, run on a normal JVM

A small application with one conditional bean is enough to see what AOT generates and what it fixes in place. The bean exists only when shop.greeting.enabled=true:

Java
package nativeaot.shop;

import java.util.Map;
import org.springframework.aot.AotDetector;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ShopApp {

    public record Greeter(String text) {
    }

    @Bean
    @ConditionalOnProperty(name = "shop.greeting.enabled", havingValue = "true")
    Greeter greeter() {
        return new Greeter("welcome");
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ShopApp.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (ConfigurableApplicationContext context = app.run(args)) {
            System.out.println("    AOT mode: " + AotDetector.useGeneratedArtifacts()
                    + ", greeter bean present: " + context.containsBean("greeter")
                    + ", bean definitions: " + context.getBeanDefinitionCount());
        }
    }
}

The program below does what the Spring Boot build plugins do in their process-aot step: it runs SpringApplicationAotProcessor with the property set to true, compiles the generated sources, and then starts the application four times, with and without the generated code:

Java
package nativeaot;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import org.springframework.boot.SpringApplicationAotProcessor;
import nativeaot.shop.ShopApp;
import org.springframework.context.aot.AbstractAotProcessor;

public class AotOnTheJvm {

    public static void main(String[] args) throws Exception {
        if (args.length > 0 && args[0].equals("run")) {
            ShopApp.main(new String[] {args[1]});
            return;
        }
        Path work = Files.createTempDirectory("aot");
        Path sources = work.resolve("sources");
        Path resources = work.resolve("resources");
        Path classes = work.resolve("classes");

        System.out.println("1. AOT processing at build time, with shop.greeting.enabled=true:");
        var settings = AbstractAotProcessor.Settings.builder()
                .sourceOutput(sources).resourceOutput(resources).classOutput(classes)
                .groupId("io.cscode").artifactId("shop").build();
        new SpringApplicationAotProcessor(ShopApp.class, settings,
                new String[] {"--shop.greeting.enabled=true"}).process();

        List<Path> generated;
        try (Stream<Path> files = Files.walk(sources)) {
            generated = files.filter(Files::isRegularFile).sorted().toList();
        }
        System.out.println("  " + generated.size() + " Java source files generated, for example:");
        generated.stream().filter(p -> p.toString().contains("ShopApp"))
                .forEach(p -> System.out.println("    " + sources.relativize(p)));
        String definitions = Files.readString(sources.resolve(
                "nativeaot/shop/ShopApp__BeanDefinitions.java"));
        int start = definitions.indexOf("  public static BeanDefinition getGreeterBeanDefinition");
        System.out.println("  from ShopApp__BeanDefinitions.java:");
        System.out.println(definitions.substring(start, definitions.indexOf("  }", start) + 3));
        try (Stream<Path> files = Files.walk(classes)) {
            files.filter(Files::isRegularFile).sorted()
                    .forEach(p -> System.out.println("  class " + classes.relativize(p)));
        }
        Path nativeImage = resources.resolve("META-INF/native-image/io.cscode/shop");
        System.out.println("  native-image.properties: "
                + Files.readString(nativeImage.resolve("native-image.properties"))
                        .replace("\\\n", ""));
        String metadata = Files.readString(nativeImage.resolve("reachability-metadata.json"));
        System.out.println("  reachability-metadata.json: "
                + (metadata.split("\"type\":", -1).length - 1) + " type entries, sections "
                + metadata.lines().filter(l -> l.matches("  \"\\w+\": \\[.*"))
                        .map(l -> l.trim().substring(0, l.trim().indexOf(':'))).toList());

        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        List<String> javacArgs = new ArrayList<>(List.of("-d", classes.toString(),
                "-cp", classes + File.pathSeparator + System.getProperty("java.class.path"),
                "-proc:none", "-nowarn"));
        generated.forEach(p -> javacArgs.add(p.toString()));
        int result = javac.run(null, null, null, javacArgs.toArray(String[]::new));
        System.out.println("  compiled the generated sources, javac exit code " + result);

        String cp = classes + File.pathSeparator + resources + File.pathSeparator
                + System.getProperty("java.class.path");
        System.out.println("2. Running the application:");
        for (String[] variant : new String[][] {
                {"plain JVM, greeting enabled ", "false", "--shop.greeting.enabled=true"},
                {"plain JVM, greeting disabled", "false", "--shop.greeting.enabled=false"},
                {"AOT mode,  greeting enabled ", "true", "--shop.greeting.enabled=true"},
                {"AOT mode,  greeting disabled", "true", "--shop.greeting.enabled=false"}}) {
            System.out.println("  " + variant[0] + ":");
            System.out.flush();
            String java = ProcessHandle.current().info().command().orElseThrow();
            ProcessBuilder child = new ProcessBuilder(java, "-Dspring.aot.enabled=" + variant[1],
                    "-cp", cp, AotOnTheJvm.class.getName(), "run", variant[2]);
            child.environment().remove("JAVA_TOOL_OPTIONS");
            child.inheritIO().start().waitFor();
        }

    }
}
Output
1. AOT processing at build time, with shop.greeting.enabled=true:
  28 Java source files generated, for example:
    nativeaot/shop/ShopApp__ApplicationContextInitializer.java
    nativeaot/shop/ShopApp__BeanDefinitions.java
    nativeaot/shop/ShopApp__BeanFactoryRegistrations.java
  from ShopApp__BeanDefinitions.java:
  public static BeanDefinition getGreeterBeanDefinition() {
    RootBeanDefinition beanDefinition = new RootBeanDefinition(ShopApp.Greeter.class);
    beanDefinition.setFactoryBeanName("shopApp");
    beanDefinition.setInstanceSupplier(getGreeterInstanceSupplier());
    return beanDefinition;
  }
  class nativeaot/shop/ShopApp$$SpringCGLIB$$0.class
  class nativeaot/shop/ShopApp$$SpringCGLIB$$FastClass$$0.class
  class nativeaot/shop/ShopApp$$SpringCGLIB$$FastClass$$1.class
  native-image.properties: Args = -H:Class=nativeaot.shop.ShopApp --no-fallback
  reachability-metadata.json: 223 type entries, sections ["reflection", "resources"]
  compiled the generated sources, javac exit code 0
2. Running the application:
  plain JVM, greeting enabled :
    AOT mode: false, greeter bean present: true, bean definitions: 51
  plain JVM, greeting disabled:
    AOT mode: false, greeter bean present: false, bean definitions: 50
  AOT mode,  greeting enabled :
    AOT mode: true, greeter bean present: true, bean definitions: 47
  AOT mode,  greeting disabled:
    AOT mode: true, greeter bean present: true, bean definitions: 47
  • AOT processing generated 28 Java source files. ShopApp__ApplicationContextInitializer is the entry point the runtime looks for, and ShopApp__BeanDefinitions holds plain Java code for each bean, such as getGreeterBeanDefinition(), which names the factory bean shopApp and an instance supplier instead of a method to find by reflection.
  • The configuration class's CGLIB subclass was generated as bytecode, ShopApp$$SpringCGLIB$$0.class, because a native image cannot generate classes at runtime.
  • native-image.properties tells GraalVM the main class and --no-fallback. reachability-metadata.json lists 223 types with reflection and resources sections: the hints for Spring Boot, Logback and the application itself.
  • On the plain JVM, the property decided at startup: the greeter existed with true and not with false.
  • With -Dspring.aot.enabled=true, the application used the generated initializer. The greeter existed in both runs, because the condition was evaluated once, at build time, with true. Passing false at runtime changed nothing.
  • AOT mode registered 47 bean definitions instead of 51: the post-processors that parse configuration classes and evaluate conditions are not needed when the result is already compiled in.

The fixed conditions are the main design constraint. @Profile, @ConditionalOnProperty and .enabled properties that decide whether a bean exists take their build-time value, so build the image with the profiles it will run with. Property values that beans merely read, such as a URL or a timeout, still come from the environment at runtime.

Runtime hints: telling GraalVM about dynamic code

A tax plugin whose class name comes from configuration is a typical case the analysis cannot follow: nothing in the code names the class directly. A RuntimeHintsRegistrar declares what will be needed, and RuntimeHintsPredicates checks the result, which is how such hints are tested in a unit test:

Java
package nativeaot.hints;

import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import org.springframework.aot.nativex.FileNativeConfigurationWriter;

public class RuntimeHintsDemo {

    /** Loaded by name from configuration, so static analysis cannot see it. */
    public static class TaxPlugin {
        public TaxPlugin() {
        }

        public double rate() {
            return 0.2;
        }
    }

    /** What a library or an application registers through META-INF/spring/aot.factories. */
    static class ShopHints implements RuntimeHintsRegistrar {
        @Override
        public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
            hints.reflection().registerType(TaxPlugin.class,
                    MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
                    MemberCategory.INVOKE_PUBLIC_METHODS);
            hints.resources().registerPattern("templates/*.html");
            hints.proxies().registerJdkProxy(Runnable.class);
        }
    }

    public static void main(String[] args) throws Exception {
        RuntimeHints hints = new RuntimeHints();
        new ShopHints().registerHints(hints, RuntimeHintsDemo.class.getClassLoader());

        System.out.println("Checks with RuntimeHintsPredicates:");
        System.out.println("  constructor of TaxPlugin invocable: " + RuntimeHintsPredicates
                .reflection().onType(TaxPlugin.class)
                .withMemberCategory(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS).test(hints));
        System.out.println("  rate() invocable: " + RuntimeHintsPredicates.reflection()
                .onMethodInvocation(TaxPlugin.class.getMethod("rate")).test(hints));
        System.out.println("  templates/invoice.html included: " + RuntimeHintsPredicates
                .resource().forResource("templates/invoice.html").test(hints));
        System.out.println("  static/logo.png included: " + RuntimeHintsPredicates
                .resource().forResource("static/logo.png").test(hints));
        System.out.println("  JDK proxy for Runnable: " + RuntimeHintsPredicates
                .proxies().forInterfaces(Runnable.class).test(hints));

        Path dir = Files.createTempDirectory("hints");
        new FileNativeConfigurationWriter(dir, "io.cscode", "shop").write(hints);
        Path json = dir.resolve("META-INF/native-image/io.cscode/shop/reachability-metadata.json");
        System.out.println("Written to META-INF/native-image/io.cscode/shop/"
                + json.getFileName() + ":");
        System.out.println(Files.readString(json));
    }
}
Output
Checks with RuntimeHintsPredicates:
  constructor of TaxPlugin invocable: true
  rate() invocable: true
  templates/invoice.html included: true
  static/logo.png included: false
  JDK proxy for Runnable: true
Written to META-INF/native-image/io.cscode/shop/reachability-metadata.json:
{
  "comment": "Spring Framework 7.0.10",
  "reflection": [
    {
      "type": "nativeaot.hints.RuntimeHintsDemo$TaxPlugin",
      "allPublicConstructors": true,
      "allPublicMethods": true
    },
    {
      "type": {
        "proxy": [
          "java.lang.Runnable"
        ]
      }
    }
  ],
  "resources": [
    {
      "glob": "\/"
    },
    {
      "glob": "templates"
    },
    {
      "glob": "templates\/*.html"
    }
  ]
}
  • The reflection hint with INVOKE_PUBLIC_CONSTRUCTORS and INVOKE_PUBLIC_METHODS covers both the constructor and rate().
  • The resource pattern templates/*.html matched templates/invoice.html but not static/logo.png, which would be missing from the executable.
  • The JDK proxy hint for Runnable lets the native image create Proxy instances for that interface.
  • FileNativeConfigurationWriter wrote the same hints in GraalVM's format: allPublicConstructors and allPublicMethods for the type, the proxy as a special type entry, and globs for the resources, including the directories that lead to them.

Spring Framework 7.0 writes all hints into one reachability-metadata.json, the format of current GraalVM versions; older setups produced separate files such as reflect-config.json and resource-config.json. Java serialization hints, RuntimeHints.serialization(), are deprecated for removal in Spring Framework 7.0: the compiler reported it when this program first used them. A registrar is activated with @ImportRuntimeHints(ShopHints.class) on a configuration class, or listed in META-INF/spring/aot.factories by a library.

Hints Spring infers, and the ones it cannot

Most applications write few hints, because the AOT engine infers them from bean definitions and annotations. This program runs the engine directly on a plain Spring context and asks which classes received hints:

Java
package nativeaot.inferred;

import org.springframework.aot.generate.ClassNameGenerator;
import org.springframework.aot.generate.DefaultGenerationContext;
import org.springframework.aot.generate.InMemoryGeneratedFiles;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.aot.ApplicationContextAotGenerator;
import org.springframework.javapoet.ClassName;

public class HintsFromAot {

    public record OrderDto(long id, String item) {
    }

    public record InvoiceDto(long id, double total) {
    }

    public static class PluginLoader {
        public Object load(String className) throws ReflectiveOperationException {
            return Class.forName(className).getDeclaredConstructor().newInstance();
        }
    }

    public static class OrderClient {
        @RegisterReflectionForBinding(OrderDto.class)
        public String fetch() {
            return "would bind JSON to OrderDto here";
        }
    }

    @Configuration
    public static class AppConfig {
        @Bean
        public OrderClient orderClient() {
            return new OrderClient();
        }

        @Bean
        public PluginLoader pluginLoader() {
            return new PluginLoader();
        }
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(AppConfig.class);

        DefaultGenerationContext generation = new DefaultGenerationContext(
                new ClassNameGenerator(ClassName.get(AppConfig.class)),
                new InMemoryGeneratedFiles());
        ClassName initializer = new ApplicationContextAotGenerator()
                .processAheadOfTime(context, generation);
        generation.writeGeneratedContent();
        RuntimeHints hints = generation.getRuntimeHints();

        System.out.println("Generated initializer: " + initializer.simpleName());
        System.out.println("Hints inferred by the AOT engine:");
        System.out.println("  OrderDto, from @RegisterReflectionForBinding: "
                + RuntimeHintsPredicates.reflection().onType(OrderDto.class).test(hints));
        System.out.println("  OrderDto accessor id() invocable: " + RuntimeHintsPredicates
                .reflection().onMethodInvocation(OrderDto.class, "id").test(hints));
        System.out.println("  InvoiceDto, only used through Class.forName: "
                + RuntimeHintsPredicates.reflection().onType(InvoiceDto.class).test(hints));
        System.out.println("  AppConfig (a configuration class): " + RuntimeHintsPredicates
                .reflection().onType(AppConfig.class).test(hints));
        System.out.println("Reflection hints recorded in total: "
                + hints.reflection().typeHints().count());
    }
}
Output
Generated initializer: HintsFromAot_AppConfig__ApplicationContextInitializer
Hints inferred by the AOT engine:
  OrderDto, from @RegisterReflectionForBinding: true
  OrderDto accessor id() invocable: true
  InvoiceDto, only used through Class.forName: false
  AppConfig (a configuration class): true
Reflection hints recorded in total: 134
  • ApplicationContextAotGenerator generated HintsFromAot_AppConfig__ApplicationContextInitializer, the same kind of entry point Spring Boot's processor produced above.
  • OrderDto received a reflection hint, including its id() accessor, because @RegisterReflectionForBinding(OrderDto.class) asks for what JSON binding with Jackson needs.
  • InvoiceDto, which the code only reaches through Class.forName(className), received nothing. In a native image, loading it would fail with ClassNotFoundException or a missing reflection error, although the JVM run works fine.
  • The configuration class itself was covered, and 134 reflection hints were recorded in total for this tiny context.

Hints are inferred for beans, their constructors and injection points, @Reflective methods, @RegisterReflectionForBinding types, and types that Spring MVC controllers return and accept. They are not inferred for class names in strings, for files read with getResourceAsStream under arbitrary names, or for libraries without metadata. The GraalVM Reachability Metadata Repository, which the native build tools use by default, supplies hints for many popular libraries.

Building a native executable or image

The commands come from the Spring Boot 4 reference documentation and were not run on this page. Both routes start from a project that applies the GraalVM Native Build Tools plugin next to the Spring Boot plugin. With Maven and spring-boot-starter-parent, the native profile is already defined, so declaring the plugin is enough:

XML
<plugin>
    <groupId>org.graalvm.buildtools</groupId>
    <artifactId>native-maven-plugin</artifactId>
</plugin>
Native build commands
GoalMavenGradle
Native executable with a local GraalVMmvn -Pnative native:compilegradle nativeCompile
Container image with a native executable, through Buildpacksmvn -Pnative spring-boot:build-imagegradle bootBuildImage
Run the tests as a native executablemvn -PnativeTest testgradle nativeTest
  • Java version: Spring Boot 4 asks for at least JDK 25 for native builds, because Buildpacks use the native-image version matching the Java version the code was compiled with.
  • Local GraalVM: native:compile needs a GraalVM distribution, such as Liberica NIK 25, installed and active. The executable lands in target, or build/native/nativeCompile with Gradle.
  • Buildpacks: build-image needs only Docker; the builder downloads GraalVM inside its container. In Gradle, applying org.graalvm.buildtools.native is enough to make bootBuildImage produce a native image.
  • AOT on the JVM: the generated code can also be packaged into a normal jar and used with -Dspring.aot.enabled=true, as the first program did, for part of the startup gain without a native build.

Common native image problems

  • Works on the JVM, fails native: a class or resource reached only dynamically, as with InvoiceDto above. Run the tests with nativeTest, add a RuntimeHintsRegistrar, or run the application on the JVM with the GraalVM tracing agent (-agentlib:native-image-agent) to record what it touches.
  • A bean that should exist does not, or the other way round: a profile or @ConditionalOnProperty evaluated with build-time values, as the greeter showed. Move the decision inside the bean, reading the property at runtime, when it must stay changeable.
  • Long builds and memory errors: native compilation of a typical service takes minutes and several gigabytes of memory. Build in CI on a large machine and keep the JVM build for everyday development.
  • Lower throughput under steady load: without the JIT's runtime profiling, peak performance can be lower than on a warmed-up JVM. Oracle GraalVM's profile-guided optimisation narrows the gap; measure your own workload before switching.
  • Libraries that generate code at runtime: bytecode generation and arbitrary dynamic class loading do not work in a native image. Check that each library supports native images, or has metadata in the reachability repository.

Choosing between JVM, AOT and native

Deployment styles and where each fits
SituationChoose
Long-running services where throughput matters mostThe plain JVM
Faster startup without changing the build muchAOT on the JVM, -Dspring.aot.enabled=true, or class data sharing
Serverless functions, scale-to-zero, command-line toolsNative image
Fast startup that keeps the JIT and full Java dynamismCRaC checkpoint and restore on a CRaC-enabled JDK
Applications that rely on runtime profiles or conditionsThe JVM, or rework those decisions before going native
Libraries with heavy reflection and no native metadataThe JVM, until the library supports native images

Native images trade build time and some dynamism for startup speed and memory. Try AOT on the JVM first: it shows every closed-world problem without the long native build. The CRaC page covers the checkpoint alternative, and Docker for Spring Boot covers packaging either kind of application into an image.