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
- 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.
| Aspect | Plain JVM | AOT on the JVM | Native image |
|---|---|---|---|
| Bean definitions | Computed at startup | Generated at build time | Generated at build time |
| Conditions and profiles | Evaluated at startup | Fixed at build time | Fixed at build time |
| Startup work | Scanning, parsing and condition evaluation | Skips configuration parsing | Skips that and class loading and JIT warm-up as well |
| Peak throughput | Best, after JIT warm-up | Same as JVM | Often lower without profile-guided optimisation |
| Build time | Fast | Slightly longer | Minutes, and several GB of memory |
| Reflection and dynamic proxies | Unrestricted | Unrestricted | Only 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
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-aotSpringApplicationAotProcessortrue
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();
}
}
}
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.
is the entry point the runtime looks for, andShopApp__ApplicationContextInitializer holds plain Java code for each bean, such asShopApp__BeanDefinitions , which names the factory beangetGreeterBeanDefinition() and an instance supplier instead of a method to find by reflection.shopApp - The configuration class's CGLIB subclass was generated as bytecode,
, because a native image cannot generate classes at runtime.ShopApp$$SpringCGLIB$$0.class tells GraalVM the main class andnative-image.properties .--no-fallback lists 223 types withreachability-metadata.json andreflection sections: the hints for Spring Boot, Logback and the application itself.resources- On the plain JVM, the property decided at startup: the greeter existed with
and not withtrue .false - With
, the application used the generated initializer. The greeter existed in both runs, because the condition was evaluated once, at build time, with-Dspring.aot.enabled=true . Passingtrue at runtime changed nothing.false - 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.enabled
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 RuntimeHintsRegistrarRuntimeHintsPredicates
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));
}
}
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
andINVOKE_PUBLIC_CONSTRUCTORS covers both the constructor andINVOKE_PUBLIC_METHODS .rate() - The resource pattern
matchedtemplates/*.html but nottemplates/invoice.html , which would be missing from the executable.static/logo.png - The JDK proxy hint for
lets the native image createRunnable instances for that interface.Proxy wrote the same hints in GraalVM's format:FileNativeConfigurationWriter andallPublicConstructors for the type, the proxy as a special type entry, and globs for the resources, including the directories that lead to them.allPublicMethods
Spring Framework 7.0 writes all hints into one reachability-metadata.jsonreflect-config.jsonresource-config.jsonRuntimeHints.serialization()@ImportRuntimeHints(ShopHints.class)META-INF/spring/aot.factories
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:
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());
}
}
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
generatedApplicationContextAotGenerator , the same kind of entry point Spring Boot's processor produced above.HintsFromAot_AppConfig__ApplicationContextInitializer received a reflection hint, including itsOrderDto accessor, becauseid() asks for what JSON binding with Jackson needs.@RegisterReflectionForBinding(OrderDto.class) , which the code only reaches throughInvoiceDto , received nothing. In a native image, loading it would fail withClass.forName(className) or a missing reflection error, although the JVM run works fine.ClassNotFoundException- 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@RegisterReflectionForBindinggetResourceAsStream
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-parentnative
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
| Goal | Maven | Gradle |
|---|---|---|
| Native executable with a local GraalVM | mvn -Pnative native:compile | gradle nativeCompile |
| Container image with a native executable, through Buildpacks | mvn -Pnative spring-boot:build-image | gradle bootBuildImage |
| Run the tests as a native executable | mvn -PnativeTest test | gradle 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:
needs a GraalVM distribution, such as Liberica NIK 25, installed and active. The executable lands innative:compile , ortarget with Gradle.build/native/nativeCompile - Buildpacks:
needs only Docker; the builder downloads GraalVM inside its container. In Gradle, applyingbuild-image is enough to makeorg.graalvm.buildtools.native produce a native image.bootBuildImage - AOT on the JVM: the generated code can also be packaged into a normal jar and used with
, as the first program did, for part of the startup gain without a native build.-Dspring.aot.enabled=true
Common native image problems
- Works on the JVM, fails native: a class or resource reached only dynamically, as with
above. Run the tests withInvoiceDto , add anativeTest , or run the application on the JVM with the GraalVM tracing agent (RuntimeHintsRegistrar ) to record what it touches.-agentlib:native-image-agent - A bean that should exist does not, or the other way round: a profile or
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.@ConditionalOnProperty - 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
| Situation | Choose |
|---|---|
| Long-running services where throughput matters most | The plain JVM |
| Faster startup without changing the build much | AOT on the JVM, -Dspring.aot.enabled=true |
| Serverless functions, scale-to-zero, command-line tools | Native image |
| Fast startup that keeps the JIT and full Java dynamism | CRaC checkpoint and restore on a CRaC-enabled JDK |
| Applications that rely on runtime profiles or conditions | The JVM, or rework those decisions before going native |
| Libraries with heavy reflection and no native metadata | The 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