APITROVE BLOG

How to build Native Images with GraalVM using Spring Boot: Basic introduction along with advanced configurations

Overview:

In this article, we shall explain how to use graalvm and spring boot to build native images.

We shall also brifely describle some advanced graalvm configuration options along with common mistakes that we need to take into account.

GraalVM and native images will be explained at some other time.


Note: You can access the sample code in this github repo

Steps:

1- in your spring boot project, add the following maven plugin:

  <plugin>
       <groupId>org.graalvm.buildtools</groupId>
       <artifactId>native-maven-plugin</artifactId>
  </plugin>

2- run the following command to compile your application with graalvm into native image(use mvn if you have maven installed in your system)

./mvn -Pnative native:compile

3- you can access the compiled file in target folder. Run the following command to run the file:

./target/compiled_file_name

Your compiled file will start running.


Additional spring boot configurations:

1- Providing hints

Older versions of spring boot(<3.2.3) require hints for serialization, reflection, proxy resources etc(see official spring boot doucmentation). Otherwise, graalVM compilation throws errors.

For example, to provide hints for serializable class, we define hints in separate class:

public class ApplicationHints implements RuntimeHintsRegistrar{

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {

        // registers serializable record
        hints.serialization().registerType(UserName.class);
    } 
}

After you have added hints, add the annotation "@EnableRuntimeHints(ApplicationHints.class)" below "@SpringBootApplication" annotation in spring boot main class.

Compile your application as mentioned in above steps and you are good to go.

2- How to add configure advanced GraalVM options in spring boot

GraalVM provides command line options that we can configure into spring boot application.

To do so, use the following lines in graalvm plugin(you can replace plugin lines entirely if you wish):

<plugin>
                <groupId>org.graalvm.buildtools</groupId>
                <artifactId>native-maven-plugin</artifactId>
                <configuration>
                    <imageName>${project.artifactId}##${project.version}</imageName>
                    <quickBuild>false</quickBuild>
                    <skipNativeTests>false</skipNativeTests>
                    <buildArgs>
                        <buildArg>graalvm_option</buildArg>
                    </buildArgs>
                </configuration>
            </plugin>

for example, to control the build optimization for fastest build, we use following option:

<buildArg>-Ob</buildArg>

Here is the complete list of options that you can use with GraalVM