Sub topic 10
Registering runtime hints in Spring
This chapter assumes you can build a Spring Boot 3 project and know what a native executable is. It also assumes you know why the closed-world assumption means reflection, resources and proxies need metadata. Here you will learn how Spring lets your code declare that metadata, so the native build keeps what your application uses dynamically.
What a runtime hint is
GraalVM's native-image tool decides at build time which classes, methods and resources go into the executable. Code that looks up a class by name, reads a classpath file or creates a proxy is invisible to that analysis. The build leaves those things out, and the application fails when it runs.
Spring AOT processing already registers hints for the framework and for Spring-managed beans. It cannot see into your own dynamic code. A runtime hint is a declaration saying "this type is used through reflection" or "this file must be packaged". Spring collects the hints in a RuntimeHints object during AOT processing. It then writes them as GraalVM reachability metadata, the format native-image reads.
RuntimeHints exposes one registry per kind of dynamic access:
| Registry | Call | Covers |
|---|---|---|
| Reflection | `hints.reflection()` | Constructors, methods and fields reached through `java.lang.reflect` |
| Resources | `hints.resources()` | Files loaded from the classpath |
| JDK proxies | `hints.proxies()` | Interfaces passed to `java.lang.reflect.Proxy` |
| Serialization | `hints.serialization()` | Types used with Java serialization |
Hints are not loaded at runtime. They exist only in the build, and they widen what the closed-world analysis keeps.
The three ways to register hints
Spring offers three mechanisms. Choose the narrowest one that fits.
- Annotations such as
@RegisterReflectionForBindingand@Reflective. They sit next to the code that needs the hint. - A
RuntimeHintsRegistrarimported with@ImportRuntimeHints. This is the general tool and covers every registry. - A registrar listed in
META-INF/spring/aot.factories. Use this for libraries, or when no Spring configuration class owns the code.
A registrar, step by step
A RuntimeHintsRegistrar has one method, registerHints(RuntimeHints, ClassLoader). Spring calls it during AOT processing, not when the application starts. The class below uses reflection and a classpath resource, so it needs both kinds of hint.
package com.example.demo;
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) {}
}@ImportRuntimeHints goes on a @Configuration class or another bean-defining class. The registrar needs a no-argument constructor, and Spring instantiates it itself. Spring only processes the annotation on classes that AOT processing sees as bean definitions. A registrar on an unused class is silently ignored.
A MemberCategory says which members of the type stay accessible:
INVOKE_PUBLIC_CONSTRUCTORSandINVOKE_DECLARED_CONSTRUCTORSallow creating instances. "Declared" includes non-public constructors.INVOKE_PUBLIC_METHODSandINVOKE_DECLARED_METHODSallow calling methods.ACCESS_PUBLIC_FIELDSandACCESS_DECLARED_FIELDS(namedPUBLIC_FIELDSandDECLARED_FIELDSin older 6.0.x releases) allow reading and writing fields.
Request only what the code uses. Each extra member is kept in the executable and makes it bigger.
Code that depends on those hints
This component needs both hints. Without them it works on the JVM and fails in the native executable.
package com.example.demo;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
@Component
public class GreetingFactory {
public Object create() throws Exception {
String text = new ClassPathResource("templates/greeting.txt")
.getContentAsString(StandardCharsets.UTF_8)
.trim();
Class<?> type = Class.forName("com.example.demo.AppConfig$Greeting");
return type.getConstructor(String.class).newInstance(text);
}
}Put the text file at src/main/resources/templates/greeting.txt. ClassPathResource.getContentAsString needs Spring Framework 6.0.5 or later, and Spring Boot 3 includes it. In a real application you would reference AppConfig.Greeting directly. The string lookup stands in for code that reads a class name from configuration.
Two details matter:
- Resource patterns are classpath-relative, with no leading slash.
registerPatternaccepts*as a wildcard, sotemplates/*.txtincludes every text file in that directory. - A file that is not hinted is absent from the executable. The failure appears when the file is read, not at build time.
Annotations for the common cases
Writing a registrar for every JSON-bound class is tedious. @RegisterReflectionForBinding handles the typical case of types that a library such as Jackson reads and writes by reflection.
package com.example.demo;
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
import org.springframework.stereotype.Service;
@Service
@RegisterReflectionForBinding({ExternalQuote.class, ExternalQuote.Price.class})
public class QuoteClient {
public ExternalQuote parse(String json) throws Exception {
return new com.fasterxml.jackson.databind.ObjectMapper()
.readValue(json, ExternalQuote.class);
}
}The annotation registers the listed classes for binding-style reflection: constructors, methods and fields. It also follows the types that appear in their properties. Spring MVC and WebFlux controllers already get this for their request and response types, so you only need it for types that bypass those paths, such as a manual ObjectMapper call.
@Reflective is a meta-annotation. Annotate a method or class with it, or with your own annotation that is itself annotated @Reflective, and Spring registers that element for reflection. Use it when you own a custom annotation and want every use of it to be reachable.
Proxies and serialization
JDK proxies are created from a list of interfaces, and the native build must know each list in advance. Register the exact interface combination, in the exact order, that your code uses.
package com.example.demo;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
public class ProxyHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.proxies().registerJdkProxy(Runnable.class, AutoCloseable.class);
hints.serialization().registerType(java.util.ArrayList.class);
}
}Registering Runnable alone does not cover a proxy built from Runnable plus AutoCloseable. Proxies created from classes with CGLIB are different. Spring generates those classes at build time during AOT processing, so you normally do not hint them.
Registering through aot.factories
A library has no @Configuration class that applications are guaranteed to scan. In that case, list the registrar in a file named META-INF/spring/aot.factories on the classpath:
org.springframework.aot.hint.RuntimeHintsRegistrar=com.example.demo.ProxyHintsSpring Boot reads this file during AOT processing for every jar on the classpath. Applications that depend on the library get the hints without any extra setup. Separate several class names with commas.
Testing that hints are present
A missing hint shows up only in a native build, which takes minutes. You can check the hints on the JVM first. RuntimeHintsPredicates builds a predicate for each kind of access, and you assert on it against a RuntimeHints you populated yourself.
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import static org.assertj.core.api.Assertions.assertThat;
class GreetingHintsTests {
@Test
void registersReflectionAndResource() {
RuntimeHints hints = new RuntimeHints();
new AppConfig.GreetingHints()
.registerHints(hints, getClass().getClassLoader());
assertThat(RuntimeHintsPredicates.reflection()
.onType(AppConfig.Greeting.class)
.withMemberCategory(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS))
.accepts(hints);
assertThat(RuntimeHintsPredicates.resource()
.forResource("templates/greeting.txt"))
.accepts(hints);
}
}The test is in the same package as AppConfig, so it can reach the package-private GreetingHints class. This check proves only that your registrar declares the hint. It cannot prove that the registrar is wired into the application, or that no other dynamic access is missing. The native test run from the testing chapter covers those gaps.
Common errors
- Hints on the wrong class.
@ImportRuntimeHintson a class that is not a bean definition does nothing. Put it on a@Configurationclass, or useaot.factories. - Too little detail. Registering a type with no
MemberCategorymakes the class reachable by name, but not its constructors. Calls then fail withNoSuchMethodExceptionor a similar error. - Too much detail. Registering every member of every class works, but it enlarges the executable and slows the build. Hint what the code touches.
- Resource path mistakes. A leading slash, a wrong directory or a missing wildcard leaves the file out. Compare the pattern with the path inside the jar.
- Hinting nested classes by the wrong name. Use the class literal (
AppConfig.Greeting.class). When you must use a string, the nested name uses$. - Expecting hints to change runtime behavior. Hints only keep things in the executable. They do not create beans, and they do not override conditions Spring already evaluated at build time.
Choosing a mechanism
| Situation | Use |
|---|---|
| Types a library binds by reflection, such as JSON payloads | `@RegisterReflectionForBinding` |
| A method or class reached reflectively through your own annotation | `@Reflective` |
| Resources, proxies or several kinds of hint together | `RuntimeHintsRegistrar` with `@ImportRuntimeHints` |
| Hints shipped in a reusable library | `META-INF/spring/aot.factories` |
Exercise
A native executable throws a "resource not found" error for config/rules.json on startup, though the application runs correctly on the JVM. The file exists under src/main/resources/config/. What do you add, and where?
Show answer
Register the resource with a RuntimeHintsRegistrar: hints.resources().registerPattern("config/rules.json"), with no leading slash. Import it using @ImportRuntimeHints on a @Configuration class that is a bean definition, or list it in META-INF/spring/aot.factories. Rebuild the native executable, because hints apply only at build time.
Exercise
You register hints.reflection().registerType(Order.class) with no member categories. Code then calls Order.class.getConstructor().newInstance() and fails in the native executable. Why, and what is the fix?
Show answer
Registering a type without member categories makes the class reachable but does not keep its constructors invokable. Add MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS, or INVOKE_DECLARED_CONSTRUCTORS if the constructor is not public.