In Spring Boot 3 how to benefit from Spring AOT with a regular JVM application?

2.6k views Asked by At

Spring Boot 3 will release in November 2022. The release candidate 2 has already been released.

Spring Boot 3 will ship with Spring AOT. Spring AOT generates additional source code so that reflection calls will be avoided.

Spring AOT was introduced to generate GraalVM Native Images. However, in theory Spring AOT could also be used for regular JVM applications to speed up the start-up process (since regular calls should be faster than reflection calls).

Unfortunately, I didn't find anything about how to use Spring AOT for regular JVM applications in the Spring Boot 3 reference documentation. Do you know how I can profit from Spring AOT in a regular JVM application?

3

There are 3 answers

1
Pablo Gutierrez On

I think they have gone in a different direction because of this video from Spring advocate. Looks like AOT is only being used with GraalVM only.

To answer your question, you can only use AOT benefits with GraalVM.

0
Lucas Borsatto On

Two useful ways you can use AOT with Spring Boot:

Using a docker image

Besides of having Java >= 17 and Gradle >= 7.3 installed, in your build.gradle you will add the following plugin:

id 'org.graalvm.buildtools.native' version '0.9.23'

An initial build.gradle would look like this:

plugins {
id 'java'
    id 'org.springframework.boot' version '3.1.2'
    id 'io.spring.dependency-management' version '1.1.2'
    id 'org.graalvm.buildtools.native' version '0.9.23'
}

group = 'com.test'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = '17'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

That's it. Now you can build your docker image running the follwing command:

gradle bootBuildImage

Now you can run docker images to see the image you just created and running it:

docker run --rm <image_id>

Compiling it to run as a native app

In this case, you should apply the same plugin shown in the example above. Besides, you will have to have GraalVM >= 17 and Gradle >= 7.3 installed. Then, you can run the follwoing command to build it:

gradle nativeCompile

and to run your application, you can just run:

/<app_name>/build/native/nativeCompile/<app_name>

And that'all. It's important to mention that some Spring features may not work properly due to Closed World assumption, which can make reflection harder to implement.

1
schrom On

This document descibes how to run AOT code on the JRE.

Essentially, you have to build your jar like this

mvn clean compile spring-boot:process-aot package

and run it like this

java -DspringAot=true -jar your-application.jar