GraalVM Native Images are standalone executables that can be generated by processing compiled Java applications ahead-of-time. Native Images generally have a smaller memory footprint and start faster than their JVM counterparts.
1. Introducing GraalVM Native Images
GraalVM Native Images provide a new way to deploy and run Java applications. Compared to the Java Virtual Machine, native images can run with a smaller memory footprint and with much faster startup times.
They are well suited to applications that are deployed using container images and are especially interesting when combined with "Function as a service" (FaaS) platforms.
Unlike traditional applications written for the JVM, GraalVM Native Image applications require ahead-of-time processing in order to create an executable. This ahead-of-time processing involves statically analyzing your application code from its main entry point.
A GraalVM Native Image is a complete, platform-specific executable. You do not need to ship a Java Virtual Machine in order to run a native image.
If you just want to get started and experiment with GraalVM you can skip ahead to the “Developing Your First GraalVM Native Application” section and return to this section later. |
1.1. Key Differences with JVM Deployments
The fact that GraalVM Native Images are produced ahead-of-time means that there are some key differences between native and JVM based applications. The main differences are:
-
Static analysis of your application is performed at build-time from the
main
entry point. -
Code that cannot be reached when the native image is created will be removed and won’t be part of the executable.
-
GraalVM is not directly aware of dynamic elements of your code and must be told about reflection, resources, serialization, and dynamic proxies.
-
The application classpath is fixed at build time and cannot change.
-
There is no lazy class loading, everything shipped in the executables will be loaded in memory on startup.
-
There are some limitations around some aspects of Java applications that are not fully supported.
On top of those differences, Spring uses a process called Spring Ahead-of-Time processing, which imposes further limitations. Please make sure to read at least the beginning of the next section to learn about those.
The Native Image Compatibility Guide section of the GraalVM reference documentation provides more details about GraalVM limitations. |
1.2. Understanding Spring Ahead-of-Time Processing
Typical Spring Boot applications are quite dynamic and configuration is performed at runtime. In fact, the concept of Spring Boot auto-configuration depends heavily on reacting to the state of the runtime in order to configure things correctly.
Although it would be possible to tell GraalVM about these dynamic aspects of the application, doing so would undo most of the benefit of static analysis. So instead, when using Spring Boot to create native images, a closed-world is assumed and the dynamic aspects of the application are restricted.
A closed-world assumption implies, besides the limitations created by GraalVM itself, the following restrictions:
-
The beans defined in your application cannot change at runtime, meaning:
-
The Spring
@Profile
annotation and profile-specific configuration have limitations. -
Properties that change if a bean is created are not supported (for example,
@ConditionalOnProperty
and.enable
properties).
-
When these restrictions are in place, it becomes possible for Spring to perform ahead-of-time processing during build-time and generate additional assets that GraalVM can use. A Spring AOT processed application will typically generate:
-
Java source code
-
Bytecode (for dynamic proxies etc)
-
GraalVM JSON hint files:
-
Resource hints (
resource-config.json
) -
Reflection hints (
reflect-config.json
) -
Serialization hints (
serialization-config.json
) -
Java Proxy Hints (
proxy-config.json
) -
JNI Hints (
jni-config.json
)
-
1.2.1. Source Code Generation
Spring applications are composed of Spring Beans. Internally, Spring Framework uses two distinct concepts to manage beans. There are bean instances, which are the actual instances that have been created and can be injected into other beans. There are also bean definitions which are used to define attributes of a bean and how its instance should be created.
If we take a typical @Configuration
class:
@Configuration(proxyBeanMethods = false)
public class MyConfiguration {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
The bean definition is created by parsing the @Configuration
class and finding the @Bean
methods.
In the above example, we’re defining a BeanDefinition
for a singleton bean named myBean
.
We’re also creating a BeanDefinition
for the MyConfiguration
class itself.
When the myBean
instance is required, Spring knows that it must invoke the myBean()
method and use the result.
When running on the JVM, @Configuration
class parsing happens when your application starts and @Bean
methods are invoked using reflection.
When creating a native image, Spring operates in a different way.
Rather than parsing @Configuration
classes and generating bean definitions at runtime, it does it at build-time.
Once the bean definitions have been discovered, they are processed and converted into source code that can be analyzed by the GraalVM compiler.
The Spring AOT process would convert the configuration class above to code like this:
/**
* Bean definitions for {@link MyConfiguration}.
*/
public class MyConfiguration__BeanDefinitions {
/**
* Get the bean definition for 'myConfiguration'.
*/
public static BeanDefinition getMyConfigurationBeanDefinition() {
Class<?> beanType = MyConfiguration.class;
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanType);
beanDefinition.setInstanceSupplier(MyConfiguration::new);
return beanDefinition;
}
/**
* Get the bean instance supplier for 'myBean'.
*/
private static BeanInstanceSupplier<MyBean> getMyBeanInstanceSupplier() {
return BeanInstanceSupplier.<MyBean>forFactoryMethod(MyConfiguration.class, "myBean")
.withGenerator((registeredBean) -> registeredBean.getBeanFactory().getBean(MyConfiguration.class).myBean());
}
/**
* Get the bean definition for 'myBean'.
*/
public static BeanDefinition getMyBeanBeanDefinition() {
Class<?> beanType = MyBean.class;
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanType);
beanDefinition.setInstanceSupplier(getMyBeanInstanceSupplier());
return beanDefinition;
}
}
The exact code generated may differ depending on the nature of your bean definitions. |
You can see above that the generated code creates equivalent bean definitions to the @Configuration
class, but in a direct way that can be understood by GraalVM.
There is a bean definition for the myConfiguration
bean, and one for myBean
.
When a myBean
instance is required, a BeanInstanceSupplier
is called.
This supplier will invoke the myBean()
method on the myConfiguration
bean.
During Spring AOT processing your application is started up to the point that bean definitions are available. Bean instances are not created during the AOT processing phase. |
Spring AOT will generate code like this for all your bean definitions.
It will also generate code when bean post-processing is required (for example, to call @Autowired
methods).
An ApplicationContextInitializer
will also be generated which will be used by Spring Boot to initialize the ApplicationContext
when an AOT processed application is actually run.
Although AOT generated source code can be verbose, it is quite readable and can be helpful when debugging an application.
Generated source files can be found in target/spring-aot/main/sources when using Maven and build/generated/aotSources with Gradle.
|
1.2.2. Hint File Generation
In addition to generating source files, the Spring AOT engine will also generate hint files that are used by GraalVM. Hint files contain JSON data that describes how GraalVM should deal with things that it can’t understand by directly inspecting the code.
For example, you might be using a Spring annotation on a private method. Spring will need to use reflection in order to invoke private methods, even on GraalVM. When such situations arise, Spring can write a reflection hint so that GraalVM knows that even though the private method isn’t called directly, it still needs to be available in the native image.
Hint files are generated under META-INF/native-image
where they are automatically picked up by GraalVM.
Generated hint files can be found in target/spring-aot/main/resources when using Maven and build/generated/aotResources with Gradle.
|
1.2.3. Proxy Class Generation
Spring sometimes needs to generate proxy classes to enhance the code you’ve written with additional features. To do this, it uses the cglib library which directly generates bytecode.
When an application is running on the JVM, proxy classes are generated dynamically as the application runs. When creating a native image, these proxies need to be created at build-time so that they can be included by GraalVM.
Unlike source code generation, generated bytecode isn’t particularly helpful when debugging an application.
However, if you need to inspect the contents of the .class files using a tool such as javap you can find them in target/spring-aot/main/classes for Maven and build/generated/aotClasses for Gradle.
|
2. Developing Your First GraalVM Native Application
Now that we have a good overview of GraalVM Native Images and how the Spring ahead-of-time engine works, we can look at how to create an application.
There are two main ways to build a Spring Boot native image application:
-
Using Spring Boot support for Cloud Native Buildpacks to generate a lightweight container containing a native executable.
-
Using GraalVM Native Build Tools to generate a native executable.
The easiest way to start a new native Spring Boot project is to go to start.spring.io, add the “GraalVM Native Support” dependency and generate the project.
The included HELP.md file will provide getting started hints.
|
2.1. Sample Application
We need an example application that we can use to create our native image. For our purposes, the simple “Hello World!” web application that’s covered in the “getting-started.html” section will suffice.
To recap, our main application code looks like this:
@RestController
@SpringBootApplication
public class MyApplication {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
This application uses Spring MVC and embedded Tomcat, both of which have been tested and verified to work with GraalVM native images.
2.2. Building a Native Image Using Buildpacks
Spring Boot includes buildpack support for native images directly for both Maven and Gradle. This means you can just type a single command and quickly get a sensible image into your locally running Docker daemon. The resulting image doesn’t contain a JVM, instead the native image is compiled statically. This leads to smaller images.
The builder used for the images is paketobuildpacks/builder-jammy-tiny:latest .
It has small footprint and reduced attack surface, but you can also use paketobuildpacks/builder-jammy-base:latest or paketobuildpacks/builder-jammy-full:latest to have more tools available in the image if required.
|
2.2.1. System Requirements
Docker should be installed. See Get Docker for more details. Configure it to allow non-root user if you are on Linux.
You can run docker run hello-world (without sudo ) to check the Docker daemon is reachable as expected.
Check the Maven or Gradle Spring Boot plugin documentation for more details.
|
On macOS, it is recommended to increase the memory allocated to Docker to at least 8GB , and potentially add more CPUs as well.
See this Stack Overflow answer for more details.
On Microsoft Windows, make sure to enable the Docker WSL 2 backend for better performance.
|
2.2.2. Using Maven
To build a native image container using Maven you should ensure that your pom.xml
file uses the spring-boot-starter-parent
and the org.graalvm.buildtools:native-maven-plugin
.
You should have a <parent>
section that looks like this:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.6</version>
</parent>
You additionally should have this in the <build> <plugins>
section:
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
The spring-boot-starter-parent
declares a native
profile that configures the executions that need to run in order to create a native image.
You can activate profiles using the -P
flag on the command line.
If you don’t want to use spring-boot-starter-parent you’ll need to configure executions for the process-aot goal from Spring Boot’s plugin and the add-reachability-metadata goal from the Native Build Tools plugin.
|
To build the image, you can run the spring-boot:build-image
goal with the native
profile active:
$ mvn -Pnative spring-boot:build-image
2.2.3. Using Gradle
The Spring Boot Gradle plugin automatically configures AOT tasks when the GraalVM Native Image plugin is applied.
You should check that your Gradle build contains a plugins
block that includes org.graalvm.buildtools.native
.
As long as the org.graalvm.buildtools.native
plugin is applied, the bootBuildImage
task will generate a native image rather than a JVM one.
You can run the task using:
$ gradle bootBuildImage
2.2.4. Running the example
Once you have run the appropriate build command, a Docker image should be available.
You can start your application using docker run
:
$ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT
You should see output similar to the following:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.2.6)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 0.08 seconds (process running for 0.095)
The startup time differs from machine to machine, but it should be much faster than a Spring Boot application running on a JVM. |
If you open a web browser to localhost:8080
, you should see the following output:
Hello World!
To gracefully exit the application, press ctrl-c
.
2.3. Building a Native Image using Native Build Tools
If you want to generate a native executable directly without using Docker, you can use GraalVM Native Build Tools. Native Build Tools are plugins shipped by GraalVM for both Maven and Gradle. You can use them to perform a variety of GraalVM tasks, including generating a native image.
2.3.1. Prerequisites
To build a native image using the Native Build Tools, you’ll need a GraalVM distribution on your machine. You can either download it manually on the Liberica Native Image Kit page, or you can use a download manager like SDKMAN!.
Linux and macOS
To install the native image compiler on macOS or Linux, we recommend using SDKMAN!. Get SDKMAN! from sdkman.io and install the Liberica GraalVM distribution by using the following commands:
$ sdk install java 22.3.r17-nik
$ sdk use java 22.3.r17-nik
Verify that the correct version has been configured by checking the output of java -version
:
$ java -version
openjdk version "17.0.5" 2022-10-18 LTS
OpenJDK Runtime Environment GraalVM 22.3.0 (build 17.0.5+8-LTS)
OpenJDK 64-Bit Server VM GraalVM 22.3.0 (build 17.0.5+8-LTS, mixed mode)
Windows
On Windows, follow these instructions to install either GraalVM or Liberica Native Image Kit in version 22.3, the Visual Studio Build Tools and the Windows SDK. Due to the Windows related command-line maximum length, make sure to use x64 Native Tools Command Prompt instead of the regular Windows command line to run Maven or Gradle plugins.
2.3.2. Using Maven
As with the buildpack support, you need to make sure that you’re using spring-boot-starter-parent
in order to inherit the native
profile and that the org.graalvm.buildtools:native-maven-plugin
plugin is used.
With the native
profile active, you can invoke the native:compile
goal to trigger native-image
compilation:
$ mvn -Pnative native:compile
The native image executable can be found in the target
directory.
2.3.3. Using Gradle
When the Native Build Tools Gradle plugin is applied to your project, the Spring Boot Gradle plugin will automatically trigger the Spring AOT engine.
Task dependencies are automatically configured, so you can just run the standard nativeCompile
task to generate a native image:
$ gradle nativeCompile
The native image executable can be found in the build/native/nativeCompile
directory.
2.3.4. Running the Example
At this point, your application should work. You can now start the application by running it directly:
$ target/myproject
$ build/native/nativeCompile/myproject
You should see output similar to the following:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.2.6)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 0.08 seconds (process running for 0.095)
The startup time differs from machine to machine, but it should be much faster than a Spring Boot application running on a JVM. |
If you open a web browser to localhost:8080
, you should see the following output:
Hello World!
To gracefully exit the application, press ctrl-c
.
3. Testing GraalVM Native Images
When writing native image applications, we recommend that you continue to use the JVM whenever possible to develop the majority of your unit and integration tests. This will help keep developer build times down and allow you to use existing IDE integrations. With broad test coverage on the JVM, you can then focus native image testing on the areas that are likely to be different.
For native image testing, you’re generally looking to ensure that the following aspects work:
-
The Spring AOT engine is able to process your application, and it will run in an AOT-processed mode.
-
GraalVM has enough hints to ensure that a valid native image can be produced.
3.1. Testing Ahead-of-time Processing With the JVM
When a Spring Boot application runs, it attempts to detect if it is running as a native image. If it is running as a native image, it will initialize the application using the code that was generated during at build-time by the Spring AOT engine.
If the application is running on a regular JVM, then any AOT generated code is ignored.
Since the native-image
compilation phase can take a while to complete, it’s sometimes useful to run your application on the JVM but have it use the AOT generated initialization code.
Doing so helps you to quickly validate that there are no errors in the AOT generated code and nothing is missing when your application is eventually converted to a native image.
To run a Spring Boot application on the JVM and have it use AOT generated code you can set the spring.aot.enabled
system property to true
.
For example:
$ java -Dspring.aot.enabled=true -jar myapplication.jar
You need to ensure that the jar you are testing includes AOT generated code.
For Maven, this means that you should build with -Pnative to activate the native profile.
For Gradle, you need to ensure that your build includes the org.graalvm.buildtools.native plugin.
|
If your application starts with the spring.aot.enabled
property set to true
, then you have higher confidence that it will work when converted to a native image.
You can also consider running integration tests against the running application.
For example, you could use the Spring WebClient
to call your application REST endpoints.
Or you might consider using a project like Selenium to check your application’s HTML responses.
3.2. Testing With Native Build Tools
GraalVM Native Build Tools includes the ability to run tests inside a native image. This can be helpful when you want to deeply test that the internals of your application work in a GraalVM native image.
Generating the native image that contains the tests to run can be a time-consuming operation, so most developers will probably prefer to use the JVM locally. They can, however, be very useful as part of a CI pipeline. For example, you might choose to run native tests once a day.
Spring Framework includes ahead-of-time support for running tests.
All the usual Spring testing features work with native image tests.
For example, you can continue to use the @SpringBootTest
annotation.
You can also use Spring Boot test slices to test only specific parts of your application.
Spring Framework’s native testing support works in the following way:
-
Tests are analyzed in order to discover any
ApplicationContext
instances that will be required. -
Ahead-of-time processing is applied to each of these application contexts and assets are generated.
-
A native image is created, with the generated assets being processed by GraalVM.
-
The native image also includes the JUnit
TestEngine
configured with a list of the discovered tests. -
The native image is started, triggering the engine which will run each test and report results.
3.2.1. Using Maven
To run native tests using Maven, ensure that your pom.xml
file uses the spring-boot-starter-parent
.
You should have a <parent>
section that looks like this:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.6</version>
</parent>
The spring-boot-starter-parent
declares a nativeTest
profile that configures the executions that are needed to run the native tests.
You can activate profiles using the -P
flag on the command line.
If you don’t want to use spring-boot-starter-parent you’ll need to configure executions for the process-test-aot goal from the Spring Boot plugin and the test goal from the Native Build Tools plugin.
|
To build the image and run the tests, use the test
goal with the nativeTest
profile active:
$ mvn -PnativeTest test
3.2.2. Using Gradle
The Spring Boot Gradle plugin automatically configures AOT test tasks when the GraalVM Native Image plugin is applied.
You should check that your Gradle build contains a plugins
block that includes org.graalvm.buildtools.native
.
To run native tests using Gradle you can use the nativeTest
task:
$ gradle nativeTest
4. Advanced Native Images Topics
4.1. Nested Configuration Properties
Reflection hints are automatically created for configuration properties by the Spring ahead-of-time engine.
Nested configuration properties which are not inner classes, however, must be annotated with @NestedConfigurationProperty
, otherwise they won’t be detected and will not be bindable.
@ConfigurationProperties(prefix = "my.properties")
public class MyProperties {
private String name;
@NestedConfigurationProperty
private final Nested nested = new Nested();
}
where Nested
is:
public class Nested {
private int number;
}
The example above produces configuration properties for my.properties.name
and my.properties.nested.number
.
Without the @NestedConfigurationProperty
annotation on the nested
field, the my.properties.nested.number
property would not be bindable in a native image.
When using constructor binding, you have to annotate the field with @NestedConfigurationProperty
:
@ConfigurationProperties(prefix = "my.properties")
public class MyPropertiesCtor {
private final String name;
@NestedConfigurationProperty
private final Nested nested;
public MyPropertiesCtor(String name, Nested nested) {
this.name = name;
this.nested = nested;
}
}
When using records, you have to annotate the parameter with @NestedConfigurationProperty
:
@ConfigurationProperties(prefix = "my.properties")
public record MyPropertiesRecord(String name, @NestedConfigurationProperty Nested nested) {
}
When using Kotlin, you need to annotate the parameter of a data class with @NestedConfigurationProperty
:
@ConfigurationProperties(prefix = "my.properties")
data class MyPropertiesKotlin(
val name: String,
@NestedConfigurationProperty val nested: Nested
)
Please use public getters and setters in all cases, otherwise the properties will not be bindable. |
4.2. Converting a Spring Boot Executable Jar
It is possible to convert a Spring Boot executable jar into a native image as long as the jar contains the AOT generated assets. This can be useful for a number of reasons, including:
-
You can keep your regular JVM pipeline and turn the JVM application into a native image on your CI/CD platform.
-
As
native-image
does not support cross-compilation, you can keep an OS neutral deployment artifact which you convert later to different OS architectures.
You can convert a Spring Boot executable jar into a native image using Cloud Native Buildpacks, or using the native-image
tool that is shipped with GraalVM.
Your executable jar must include AOT generated assets such as generated classes and JSON hint files. |
4.2.1. Using Buildpacks
Spring Boot applications usually use Cloud Native Buildpacks through the Maven (mvn spring-boot:build-image
) or Gradle (gradle bootBuildImage
) integrations.
You can, however, also use pack
to turn an AOT processed Spring Boot executable jar into a native container image.
First, make sure that a Docker daemon is available (see Get Docker for more details). Configure it to allow non-root user if you are on Linux.
You also need to install pack
by following the installation guide on buildpacks.io.
Assuming an AOT processed Spring Boot executable jar built as myproject-0.0.1-SNAPSHOT.jar
is in the target
directory, run:
$ pack build --builder paketobuildpacks/builder-jammy-tiny \
--path target/myproject-0.0.1-SNAPSHOT.jar \
--env 'BP_NATIVE_IMAGE=true' \
my-application:0.0.1-SNAPSHOT
You do not need to have a local GraalVM installation to generate an image in this way. |
Once pack
has finished, you can launch the application using docker run
:
$ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT
4.2.2. Using GraalVM native-image
Another option to turn an AOT processed Spring Boot executable jar into a native executable is to use the GraalVM native-image
tool.
For this to work, you’ll need a GraalVM distribution on your machine.
You can either download it manually on the Liberica Native Image Kit page or you can use a download manager like SDKMAN!.
Assuming an AOT processed Spring Boot executable jar built as myproject-0.0.1-SNAPSHOT.jar
is in the target
directory, run:
$ rm -rf target/native
$ mkdir -p target/native
$ cd target/native
$ jar -xvf ../myproject-0.0.1-SNAPSHOT.jar
$ native-image -H:Name=myproject @META-INF/native-image/argfile -cp .:BOOT-INF/classes:`find BOOT-INF/lib | tr '\n' ':'`
$ mv myproject ../
These commands work on Linux or macOS machines, but you will need to adapt them for Windows. |
The @META-INF/native-image/argfile might not be packaged in your jar.
It is only included when reachability metadata overrides are needed.
|
The native-image -cp flag does not accept wildcards.
You need to ensure that all jars are listed (the command above uses find and tr to do this).
|
4.3. Using the Tracing Agent
The GraalVM native image tracing agent allows you to intercept reflection, resources or proxy usage on the JVM in order to generate the related hints. Spring should generate most of these hints automatically, but the tracing agent can be used to quickly identify the missing entries.
When using the agent to generate hints for a native image, there are a couple of approaches:
-
Launch the application directly and exercise it.
-
Run application tests to exercise the application.
The first option is interesting for identifying the missing hints when a library or a pattern is not recognized by Spring.
The second option sounds more appealing for a repeatable setup, but by default the generated hints will include anything required by the test infrastructure. Some of these will be unnecessary when the application runs for real. To address this problem the agent supports an access-filter file that will cause certain data to be excluded from the generated output.
4.3.1. Launch the Application Directly
Use the following command to launch the application with the native image tracing agent attached:
$ java -Dspring.aot.enabled=true \
-agentlib:native-image-agent=config-output-dir=/path/to/config-dir/ \
-jar target/myproject-0.0.1-SNAPSHOT.jar
Now you can exercise the code paths you want to have hints for and then stop the application with ctrl-c
.
On application shutdown the native image tracing agent will write the hint files to the given config output directory.
You can either manually inspect these files, or use them as input to the native image build process.
To use them as input, copy them into the src/main/resources/META-INF/native-image/
directory.
The next time you build the native image, GraalVM will take these files into consideration.
There are more advanced options which can be set on the native image tracing agent, for example filtering the recorded hints by caller classes, etc. For further reading, please see the official documentation.
4.4. Custom Hints
If you need to provide your own hints for reflection, resources, serialization, proxy usage etc. you can use the RuntimeHintsRegistrar
API.
Create a class that implements the RuntimeHintsRegistrar
interface, and then make appropriate calls to the provided RuntimeHints
instance:
public class MyRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
// Register method for reflection
Method method = ReflectionUtils.findMethod(MyClass.class, "sayHello", String.class);
hints.reflection().registerMethod(method, ExecutableMode.INVOKE);
// Register resources
hints.resources().registerPattern("my-resource.txt");
// Register serialization
hints.serialization().registerType(MySerializableClass.class);
// Register proxy
hints.proxies().registerJdkProxy(MyInterface.class);
}
}
You can then use @ImportRuntimeHints
on any @Configuration
class (for example your @SpringBootApplication
annotated application class) to activate those hints.
If you have classes which need binding (mostly needed when serializing or deserializing JSON), you can use @RegisterReflectionForBinding
on any bean.
Most of the hints are automatically inferred, for example when accepting or returning data from a @RestController
method.
But when you work with WebClient
, RestClient
or RestTemplate
directly, you might need to use @RegisterReflectionForBinding
.
4.4.1. Testing custom hints
The RuntimeHintsPredicates
API can be used to test your hints.
The API provides methods that build a Predicate
that can be used to test a RuntimeHints
instance.
If you’re using AssertJ, your test would look like this:
class MyRuntimeHintsTests {
@Test
void shouldRegisterHints() {
RuntimeHints hints = new RuntimeHints();
new MyRuntimeHints().registerHints(hints, getClass().getClassLoader());
assertThat(RuntimeHintsPredicates.resource().forResource("my-resource.txt")).accepts(hints);
}
}
4.5. Known Limitations
GraalVM native images are an evolving technology and not all libraries provide support. The GraalVM community is helping by providing reachability metadata for projects that don’t yet ship their own. Spring itself doesn’t contain hints for 3rd party libraries and instead relies on the reachability metadata project.
If you encounter problems when generating native images for Spring Boot applications, please check the Spring Boot with GraalVM page of the Spring Boot wiki. You can also contribute issues to the spring-aot-smoke-tests project on GitHub which is used to confirm that common application types are working as expected.
If you find a library which doesn’t work with GraalVM, please raise an issue on the reachability metadata project.
5. What to Read Next
If you want to learn more about the ahead-of-time processing provided by our build plugins, see the Maven and Gradle plugin documentation.
To learn more about the APIs used to perform the processing, browse the org.springframework.aot.generate
and org.springframework.beans.factory.aot
packages of the Spring Framework sources.
For known limitations with Spring and GraalVM, please see the Spring Boot wiki.
The next section goes on to cover the Spring Boot CLI.