Sub topic 13
Diagnosing native image failures
This chapter assumes you can build a Spring Boot 3 project with Maven or Gradle and that you know what reflection and dynamic proxies are. It also assumes you have read the earlier chapters on the closed-world assumption, Spring AOT, runtime hints and the tracing agent. Here you will learn to sort native failures into a few categories, read the evidence each one leaves, and apply the right fix.
Three places a native build can fail
A native application passes through three stages, and each stage fails in its own way.
- Spring AOT processing runs on the JVM at build time. It generates bean definitions as code and records hints.
- The
native-imagetool runs static analysis and compiles the result. It fails when it finds something it cannot handle. - The executable runs. It fails when code reaches something that the analysis did not include.
Identify the stage first. The stage tells you which tool to inspect and which kind of fix applies.
Failures during the build
Spring AOT errors
AOT processing runs the application's configuration on a JVM, so a bean method that fails on the JVM fails here too. A typical cause is a bean that needs an external resource while the context is being refreshed for AOT. The context is refreshed but not fully started, and that distinction is useful. Code in @PostConstruct methods or constructors may run at build time on some paths. If it opens a database connection or reads an environment variable that exists only in production, the build fails or bakes in the wrong value.
Fix it by moving environment-dependent work out of bean construction and into a lifecycle event that fires at run time, such as ApplicationReadyEvent or a SmartLifecycle start.
native-image analysis errors
The tool stops with an error when it finds that a class is initialized at build time in a way that is not allowed. Typical symptoms:
- A message that an object of a class "was found in the image heap" but must not be, for example a
Randomor a thread created in a static initializer. - A message that a class "should be initialized at run time" because its build-time state is unsafe.
- A
NoClassDefFoundErrorfor an optional dependency that the code references but the classpath lacks.
The first two come from static initializers that capture state such as random seeds, timestamps, or open files. Move that state into a method or a lazily created holder so it is computed at run time. For third-party code you cannot change, the build supports --initialize-at-run-time=com.example.Type. Spring Boot's native build tools accept it as a build argument:
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<configuration>
<buildArgs>
<buildArg>--initialize-at-run-time=com.example.LegacyClock</buildArg>
</buildArgs>
</configuration>
</plugin>Out of memory during compilation
Native compilation needs much more memory than a normal build. If the process is killed, or the log shows the compiler exiting without a message, check the memory limit first. Containers and CI runners with 2 GB often fail. Give the build at least 8 GB where possible, and watch for the operating system's out-of-memory killer in the system log. Close other heavy processes on a developer machine before retrying.
Failures at run time
These are the most common native-only problems. The application builds, starts or partly starts, and then fails because code reached something that was not in the image.
Reading the symptom
| Symptom | Likely cause | First fix |
|---|---|---|
| `ClassNotFoundException` for a class that exists | Class loaded by name, not registered | Register reflection hint for the type |
| `NoSuchMethodException` or `NoSuchFieldException` | Type registered without the needed members | Add the matching `MemberCategory` |
| `MissingResourceException` or a null from `getResource` | Resource not included in the image | Register a resource pattern |
| `IllegalArgumentException: ... is not an interface` or a proxy error at run time | Proxy interface set not known at build time | Register a proxy hint |
| JSON serialization produces `{}` or fails to bind | Jackson cannot see fields or constructors | Register the type for reflection |
| A bean you expect does not exist | Condition evaluated at build time | Rebuild with the right properties |
| `UnsupportedFeatureException: Defining hidden classes` or runtime class generation | Library generates bytecode at run time | Use a version with native support, or avoid the feature |
Missing reflection members
A registration that names only the type does not make its methods available. The following code fails in a native executable if Greeting is only registered by name:
import java.lang.reflect.Method;
public class Inspect {
public static void main(String[] args) throws Exception {
Class<?> type = Class.forName("com.example.AppConfig$Greeting");
Method accessor = type.getMethod("text");
System.out.println(accessor.getName());
}
}On a JVM this prints text. In an image without a hint for public methods, getMethod throws NoSuchMethodException. The hint from the earlier chapter, with MemberCategory.INVOKE_PUBLIC_METHODS, fixes it. When you see this exception, check the stack trace for the class name, then register that class with the member categories the calling code needs.
Missing resources
Files under src/main/resources are not all copied into the executable. Spring Boot registers the common ones, such as application.properties and the static content locations. A custom file read through ClassPathResource needs a pattern:
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
class TemplateHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.resources().registerPattern("templates/*.txt");
}
}Import it with @ImportRuntimeHints(TemplateHints.class) on a configuration class. Patterns are globs, so keep them as narrow as the files allow. A pattern like ** bloats the executable.
Proxies
Spring creates JDK proxies for interfaces and generates subclasses for classes at build time when it can. A proxy over an interface set that AOT never saw fails at run time. Register it explicitly:
hints.proxies().registerJdkProxy(com.example.Service.class);Library code that builds proxies from user-supplied interface lists, such as some client factories, needs this kind of hint.
Build-time surprises with no exception
Some failures throw nothing. The application starts and behaves differently from the JVM version. The usual cause is that conditions were evaluated at build time.
@ConditionalOnPropertyand@ConditionalOnBeanare resolved during AOT processing. A property you pass on the command line at launch does not add a bean that was excluded at build time.- Profiles that change the bean set must be active during the build. Activate them for AOT with the
spring.profiles.activeproperty in the build configuration, not only at run time. - Properties that only bind values, such as a server port or a database URL, still work at run time because they do not change the bean graph.
A quick check: list the generated sources under target/spring-aot/main/sources (Maven) or build/generated/aotSources (Gradle). If your bean has no definition there, it was excluded at build time. Rebuild with the intended property in place.
grep -rl "FeatureService" target/spring-aot/main/sourcesIf the command prints nothing, the build excluded the bean.
Collecting evidence
Use these tools in order, from cheapest to most expensive.
- Read the first exception in the log, not the last. Native stack traces often repeat the same cause through several wrappers.
- Run the same code on the JVM with
-Dspring.aot.enabled=true. This uses the AOT-generated code on a normal JVM, so it exposes AOT problems without a native compile. If it works on the JVM with AOT enabled and fails natively, the problem is missing reachability metadata. - Run the tracing agent against the failing path, as shown in the earlier chapter, and compare its output with the hints you have. Exercise the path that fails, or the agent will not record it.
- Run the tests natively with
./mvnw -PnativeTest test. A failing native test gives you a small, repeatable case that compiles faster than the full application. - For build failures, rerun with more detail. Maven's
-Xflag, or Gradle's--stacktrace, shows the exactnative-imagecommand and the full analysis error.
Library compatibility
Many failures come from third-party libraries, not your code. Before writing hints by hand, check three things.
- Does the library publish its own metadata? Recent versions of many libraries include it inside the jar under
META-INF/native-image. - Is it covered by the GraalVM Reachability Metadata Repository? The native build plugins consult it by default, so upgrading the plugin or the library can fix a failure without any code change.
- Does the library depend on runtime bytecode generation or on
Unsafetricks? Such libraries often cannot work in a native image at all. Look for an alternative or a version made for AOT.
Working through a failure
Suppose a native executable starts and then throws NoSuchMethodException: com.example.Order.<init>() on the first request that binds JSON.
- The stage is run time, and the message names a constructor, so metadata is missing.
- Run on the JVM with AOT enabled. It works, which confirms a metadata gap.
- Jackson instantiates
Orderby reflection, so register it withMemberCategory.INVOKE_PUBLIC_CONSTRUCTORSand, if it reads fields,DECLARED_FIELDS. - Rebuild natively, repeat the request, and add a native test that posts the same JSON so the fix stays covered.
Spring offers @RegisterReflectionForBinding(Order.class) for exactly this case of types used for data binding. It is shorter than a registrar and is the first thing to try for request and response types.
Exercise
A native executable returns a feature endpoint that works on the JVM, but the FeatureService bean is missing in the native build. The app.feature.enabled=true property is passed as an environment variable only when the executable starts. What is the cause, and how do you confirm and fix it?
Show answer
The @ConditionalOnProperty condition is evaluated during AOT processing, so the bean was excluded because the property was absent at build time. Confirm it by searching the generated AOT sources for FeatureService and finding no definition. Fix it by setting app.feature.enabled=true in the build configuration (for example in application.properties or the AOT arguments) and rebuilding.
Exercise
An application passes all JVM tests but throws NoSuchMethodException for a record accessor in the native executable. What single check tells you whether the cause is Spring AOT or missing reachability metadata?
Show answer
Run the application on a JVM with -Dspring.aot.enabled=true. If it works there, the AOT-generated code is correct and the native failure comes from missing reachability metadata, so add a reflection hint with the needed member categories.