Sub topic 11
Collecting metadata with the tracing agent
This chapter assumes you can build a Spring Boot 3 project with Maven or Gradle, that you know what reflection and dynamic proxies are, and that you have read the earlier chapters on the closed-world assumption, reachability metadata and runtime hints. You should have a GraalVM JDK installed, because the agent ships with it.
Why an agent exists
The native-image tool decides at build time which classes, methods and resources end up in the executable. Code that reaches them dynamically, through Class.forName, Method.invoke, getResourceAsStream or Proxy.newProxyInstance, is invisible to its static analysis. Without metadata that names those elements, they are missing at runtime and the application fails.
You can write that metadata by hand, or in Spring code with a RuntimeHintsRegistrar. For your own classes this is usually practical. For a library you do not control, finding every reflective access by reading source is slow and error prone.
The tracing agent solves this by observation. It is a JVMTI agent (a native plugin that attaches to the JVM) that watches a normal JVM run. It records each dynamic access it sees and writes the result as JSON metadata files in the format native-image reads.
Running the agent
The agent is enabled with a -agentlib option on a GraalVM JVM. The command below runs the packaged application and writes the metadata into the resources directory, where the build picks it up.
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image -jar target/demo.jarThe agent writes its output when the JVM exits normally. If you kill the process abruptly, you may get no files or incomplete ones. Stop the application with a clean shutdown, such as Ctrl+C, which triggers the JVM shutdown hooks, or an actuator shutdown call.
The output directory contains files such as these:
| File | Contents |
|---|---|
| `reachability-metadata.json` | Reflection, resource, proxy, serialization and JNI entries in the combined format used by recent GraalVM versions |
| `reflect-config.json` | Classes, constructors, methods and fields accessed by reflection, in the older split format |
| `resource-config.json` | Classpath resources that were loaded |
| `proxy-config.json` | Interface lists used to create JDK dynamic proxies |
| `jni-config.json` | Classes accessed from native JNI code |
| `serialization-config.json` | Classes used with Java serialization |
Which layout you get depends on your GraalVM version. Older releases write the separate *-config.json files, and newer ones can write a single combined file. Either is valid input for native-image, as long as it sits under META-INF/native-image on the classpath.
Where to put the output
The native-image tool searches the classpath for META-INF/native-image/ directories. Files inside src/main/resources/META-INF/native-image are packaged into your jar and found automatically. A subdirectory named after your group and artifact, for example META-INF/native-image/com.example/demo/, is the convention when you publish a library, because it prevents clashes between jars. For an application, the top-level directory works.
Running the agent through the build tools
Running java -agentlib by hand is fine for a first experiment. The GraalVM build tools plugins can also attach the agent to a run, which keeps the setup in the build.
With Maven, the native-maven-plugin supports an agent configuration. You enable it in the plugin's configuration and run your application or tests with the agent option. With Gradle, the org.graalvm.buildtools.native plugin lets you run ./gradlew -Pagent run or ./gradlew -Pagent test to collect metadata, and ./gradlew metadataCopy --task run --dir src/main/resources/META-INF/native-image to copy it into your sources. Option names and defaults change between plugin versions, so check the documentation for the version your project uses.
Exercising the application
The agent only records what actually happens. If a code path never runs during the trace, the metadata for it is missing, and the native executable fails when that path runs in production. Coverage of the trace is the main quality factor.
Make the trace broad:
- Call every endpoint, including error paths such as validation failures and 404 responses.
- Exercise every serialization format you support. A JSON response and an XML response use different reflective paths.
- Trigger scheduled jobs, event listeners and startup runners.
- Use each configured integration: database queries, message consumers, outbound HTTP clients.
- Run with each profile you will deploy, since profiles can activate different beans.
Running the test suite with the agent attached is a convenient way to get coverage, because tests already exercise many paths. Integration tests that start the full application context are the most useful. Unit tests that use plain objects add little.
The merge option looks like this:
java -agentlib:native-image-agent=config-merge-dir=src/main/resources/META-INF/native-image -jar target/demo.jarWhat the agent does not do
Spring already supplies most hints
A Spring Boot application is processed by Spring AOT during the build. That step generates hints for beans, auto-configuration, @ConfigurationProperties binding and many Spring and Spring Boot internals. Libraries in the Spring portfolio ship their own hints. The GraalVM Reachability Metadata Repository also supplies metadata for many popular third-party libraries, and the native build plugins fetch it by default.
So a typical Spring Boot application needs little or no agent output. The agent is for the gaps: a third-party library with no published metadata, reflection in your own code that you did not register, or resources loaded by a computed name.
The agent traces a JVM run, not the native one
The JVM and the native executable can behave differently. The agent sees what the JVM does. It cannot tell you that a class initializer runs at build time in the native image, or that a bean condition was resolved during AOT processing. Those problems need a native test run, covered in the testing chapter.
Build-time decisions are not recorded
Conditions such as @ConditionalOnProperty are evaluated when AOT processing runs. The agent runs against a JVM where those conditions are evaluated at startup. If the property differs between your trace and your build, the trace may record accesses to beans that the native image never contains, or miss beans it does contain. Run the agent with the same properties and profiles you use for the native build.
Over-collection
The agent records everything, including accesses made by the JVM itself, by the agent's own run, and by test frameworks if you trace tests. The result can include entries you do not need. Extra entries enlarge the executable and the build time slightly, and they hide which entries matter. Review the generated files before committing them. Filter noise with an access filter file, passed as access-filter-file=path/to/filter.json:
{
"rules": [
{ "excludeClasses": "org.junit.**" },
{ "excludeClasses": "org.apache.maven.surefire.**" },
{ "excludeClasses": "com.example.demo.TestOnly*" }
]
}The agent already ignores some of its own internals by default, so you only add rules for noise from your environment.
Agent output versus runtime hints
You now have two ways to supply the same kind of information. They suit different cases.
| Aspect | Tracing agent | `RuntimeHintsRegistrar` |
|---|---|---|
| Source of truth | Observed behavior of one run | Declared intent in code |
| Coverage | Only executed paths | Everything you write down |
| Maintenance | Regenerate after code changes | Lives with the code it describes |
| Review | Large JSON files, hard to diff | Small Java, reviewed like any code |
| Best for | Discovering what a third-party library needs | Your own classes and resources |
A practical workflow combines them. Use the agent to find what is missing, read the generated entries, and then translate the ones that belong to your code into a RuntimeHintsRegistrar. Keep generated JSON only for third-party needs that have no other home.
A registrar for a record and a resource looks like this:
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;
@Configuration
@ImportRuntimeHints(AppConfig.GreetingHints.class)
public class AppConfig {
static class GreetingHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerType(Greeting.class,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_METHODS);
hints.resources().registerPattern("templates/greeting.txt");
}
}
public record Greeting(String text) {}
}A worked workflow
- Build and run the application on the JVM first and confirm it works.
- Build the native executable and run it. Note each failure, such as a
ClassNotFoundExceptionor a missing resource. - For a failure in your own code, add a hint in a registrar.
- For a failure in a library, run the JVM build with the agent and exercise the failing feature, then copy the output into
META-INF/native-image. - Rebuild the native executable and repeat the failing action.
- Review the generated JSON, remove entries you do not need, and commit it.
- Run the native tests to confirm the fix holds.
Rerun the agent when you upgrade the library or change the code that uses it. Metadata for an old version of a library can be stale or incomplete for the new one.
Common problems
- No files appear. The JVM did not exit cleanly, the output directory is not writable, or you ran a JVM that is not GraalVM and does not include the agent. Check
java -versionshows a GraalVM build. - The native executable still fails on the same path. The path was not exercised during the trace, or the trace used different properties than the build. Repeat the trace with the failing action.
- Entries appear for classes you do not recognize. They come from test frameworks or the JVM. Add an access filter.
- Metadata is ignored. The files are not under
META-INF/native-imageon the build classpath, or a JSON syntax error prevents parsing. Read thenative-imagebuild output for warnings about configuration files. - Metadata that worked stops working after an upgrade. The new library version loads different classes or resource names. Trace again.
Exercise
Your Spring Boot application runs correctly on the JVM, but the native executable throws an error when a request triggers a third-party library that loads a class by name. You collect a trace by running the app with the agent, calling only the health endpoint, and stopping it with kill -9. The error remains. Give two reasons the trace did not fix it and how to correct each.
Show answer
First, kill -9 terminates the JVM without running shutdown, so the agent may not write its files. Stop the application cleanly, for example with Ctrl+C. Second, the trace called only the health endpoint, so the library code that loads the class never ran and was never recorded. Exercise the endpoint that triggers the library, and use config-merge-dir to combine this trace with earlier ones. Then rebuild the native executable and retest.
Exercise
A teammate proposes committing a large reflect-config.json produced by tracing the whole test suite, including JUnit classes. Name one problem with this and one alternative for the entries that describe your own classes.
Show answer
The file contains entries for test framework classes that the application does not need, which adds noise and makes review hard. Use an access filter to exclude them. For your own classes, replace the generated entries with a RuntimeHintsRegistrar so the hints are reviewed as Java and stay next to the code they describe.