Sub topic 8
Building native images with Maven and Gradle
This chapter assumes you can run native-image by hand and know what reachability metadata is. It also assumes you can read a basic pom.xml or build.gradle file and have a GraalVM JDK installed. Running native-image manually works for a single class. Real projects have dependencies, tests, profiles and CI, so you need the build tool to drive the compiler. Both Maven and Gradle do this through the GraalVM Native Build Tools project.
What the plugins do
The plugins don't compile Java to native code themselves. They do the work you did by hand in earlier chapters:
- Compile your sources and package the project as usual.
- Work out the classpath, including all runtime dependencies.
- Collect reachability metadata from your project, from dependencies, and from the shared GraalVM Reachability Metadata Repository.
- Run the
native-imagetool from your GraalVM installation with the right arguments. - Place the executable in the build output directory.
The plugin finds native-image through GRAALVM_HOME or JAVA_HOME. If the JDK on your path is a plain OpenJDK, the build fails because it cannot find the tool. Check this first when a native build fails immediately.
export JAVA_HOME=/path/to/graalvm
export PATH="$JAVA_HOME/bin:$PATH"
native-image --versionMaven
Put the plugin in a profile so normal builds stay fast. A native build takes much longer than a JAR build, and you don't want it on every mvn package.
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>${native.maven.plugin.version}</version>
<extensions>true</extensions>
</plugin>
</plugins>
</build>
</profile>Define the version as a property, for example <native.maven.plugin.version>0.10.4</native.maven.plugin.version> in <properties>. Then build:
mvn -Pnative native:compileThe native:compile goal first runs the lifecycle up to package, then invokes native-image. The executable appears in target/, named after the imageName setting. The default name is the artifact ID.
Configuring the image
Plugin configuration goes in a <configuration> element. The most common settings are the image name, the main class and extra native-image flags.
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>${native.maven.plugin.version}</version>
<extensions>true</extensions>
<configuration>
<imageName>app</imageName>
<mainClass>com.example.Main</mainClass>
<buildArgs>
<buildArg>--no-fallback</buildArg>
<buildArg>-O1</buildArg>
</buildArgs>
</configuration>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>compile-no-fork</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>Each <buildArg> is passed to native-image as one argument, so the flags in the table of options you already know from the command line work here. The executions block binds compile-no-fork to the package phase. With this block, mvn -Pnative package produces the executable directly. compile-no-fork skips the extra lifecycle fork that compile performs, so it is the right goal to bind to a phase.
Maven goals at a glance
| Goal | Purpose |
|---|---|
| `native:compile` | Forks the lifecycle to `package`, then builds the executable. Use it from the command line. |
| `native:compile-no-fork` | Builds the executable without forking. Bind it to a phase in `executions`. |
| `native:test` | Runs your JUnit tests as a native executable. |
| `native:metadata-copy` | Copies metadata collected by the agent into your project. |
Gradle
For Gradle, apply the org.graalvm.buildtools.native plugin next to java and application.
plugins {
id 'java'
id 'application'
id 'org.graalvm.buildtools.native' version '0.10.4'
}
repositories {
mavenCentral()
}
application {
mainClass = 'com.example.Main'
}
graalvmNative {
binaries {
main {
imageName = 'app'
buildArgs.add('--no-fallback')
buildArgs.add('-O1')
}
}
}The plugin adds these tasks:
| Task | Purpose |
|---|---|
| `nativeCompile` | Builds the executable into `build/native/nativeCompile/`. |
| `nativeRun` | Builds if needed, then runs the executable. |
| `nativeTest` | Runs the tests as a native executable. |
| `metadataCopy` | Copies agent-collected metadata into your project. |
./gradlew nativeCompile
./build/native/nativeCompile/appThe main binary is the application. The plugin also defines a test binary used by nativeTest. You can configure each separately, for example to give the test binary extra build arguments.
Gradle can also find a GraalVM through its toolchain support. If more than one JDK is installed and the build picks the wrong one, set JAVA_HOME explicitly. You can also tighten the lookup in the graalvmNative block with toolchainDetection = false, which makes the plugin use only the JDK from JAVA_HOME.
Metadata in the build
The plugins help with reachability metadata in three ways.
Your own metadata files
Files under src/main/resources/META-INF/native-image/ are packaged into your JAR. native-image reads them from the classpath automatically. This is where the hand-written reflect-config.json from the previous chapter belongs. Using a subdirectory such as META-INF/native-image/com.example/app/ keeps files from different libraries separate.
The reachability metadata repository
The plugins can download community-maintained metadata for popular libraries. It is on by default in recent plugin versions. You can control it explicitly. In Gradle:
graalvmNative {
metadataRepository {
enabled = true
}
}In Maven the equivalent is <metadataRepository><enabled>true</enabled></metadataRepository> inside <configuration>. The plugin matches the library versions on your classpath against the repository and applies the entries that fit. This removes much of the manual work for common libraries, but it covers only libraries and versions that someone has contributed.
The tracing agent
You can run the tracing agent through the build tool instead of writing the java -agentlib command yourself. The agent runs your application or your tests on a JVM, records the reflection, resource and proxy use it sees, and writes metadata files.
With Gradle:
./gradlew -Pagent run
./gradlew metadataCopy --task run --dir src/main/resources/META-INF/native-imageThe first command runs the application with the agent attached. The second copies the output into your source tree so it becomes part of the project. With Maven, enable the agent in the plugin configuration, run the tests or the application with -Pnative -Dagent=true, and copy the result with native:metadata-copy.
Running tests as native executables
nativeTest and native:test compile your JUnit tests together with your code into a native test executable and run it. This catches problems that pass on the JVM and fail natively, such as missing metadata, before you ship. Native tests are slow to build, so many teams run them in CI rather than on every local change.
Common build problems
native-imagenot found. The JDK is not GraalVM, orJAVA_HOMEpoints to the wrong one. Fix the environment variable.- Out of memory during the build. The static analysis needs a lot of RAM. Close other programs, or raise the builder's limit with a build argument such as
-J-Xmx8g. - Wrong main class. If the JAR has no
Main-Classin its manifest and you did not setmainClass, the build stops with an error. Set it in the plugin configuration. - A fallback image is produced. Without
--no-fallback, older setups may silently build an image that needs a JVM. Passing--no-fallbackturns that into a build error, which is what you want. - Works on the JVM, fails natively. Missing reachability metadata is the usual cause. Run the agent, or add entries by hand, and rebuild.
Choosing between the tools
Both plugins build the same executable with the same native-image tool. Choose the one your project already uses. The differences are in ergonomics: Maven expresses native builds as profiles and goals, while Gradle adds tasks and a graalvmNative extension. The metadata repository, the agent and native tests work in both.
Exercise
A teammate's mvn package now takes ten minutes after adding the native plugin to the main <build> section. How would you fix this without removing native support, and which command would then build the executable?
Show answer
Move the plugin into a profile, such as one with the id native, so it applies only when requested. Normal mvn package builds the JAR quickly. Build the executable with mvn -Pnative native:compile, or with mvn -Pnative package if compile-no-fork is bound to the package phase.
Exercise
Your Gradle native build succeeds, but the executable throws a ClassNotFoundException for a class loaded with Class.forName. The same code works on the JVM. What is the likely cause, and how do you collect the missing data with the build tool?
Show answer
The class is not in the reachability metadata, so static analysis did not keep it for reflection. Run ./gradlew -Pagent run, exercise the code path that calls Class.forName, then run ./gradlew metadataCopy --task run --dir src/main/resources/META-INF/native-image. Rebuild with ./gradlew nativeCompile.