references/gradle-native-plugin.md
# Gradle GraalVM Native Build Tools Plugin
Complete Gradle configuration for building GraalVM native images using the Native Build Tools plugin.
## Table of Contents
1. [Plugin Setup](#plugin-setup)
2. [Configuration Options](#configuration-options)
3. [Spring Boot Gradle Integration](#spring-boot-gradle-integration)
4. [Testing in Native Mode](#testing-in-native-mode)
5. [Multi-Project Builds](#multi-project-builds)
---
## Plugin Setup
### Kotlin DSL (`build.gradle.kts`)
```kotlin
plugins {
java
id("org.graalvm.buildtools.native") version "0.10.6"
}
graalvmNative {
binaries {
named("main") {
imageName.set(project.name)
mainClass.set("com.example.Application")
buildArgs.add("--no-fallback")
buildArgs.add("-H:+ReportExceptionStackTraces")
javaLauncher.set(javaToolchains.launcherFor {
languageVersion.set(JavaLanguageVersion.of(21))
vendor.set(JvmVendorSpec.matching("GraalVM"))
})
}
}
}
```
### Groovy DSL (`build.gradle`)
```groovy
plugins {
id 'java'
id 'org.graalvm.buildtools.native' version '0.10.6'
}
graalvmNative {
binaries {
main {
imageName = project.name
mainClass = 'com.example.Application'
buildArgs.add('--no-fallback')
buildArgs.add('-H:+ReportExceptionStackTraces')
}
}
}
```
Build with:
```bash
./gradlew nativeCompile
```
The native executable is produced in `build/native/nativeCompile/`.
## Configuration Options
### Binary Configuration
```kotlin
graalvmNative {
binaries {
named("main") {
imageName.set(project.name)
mainClass.set("com.example.Application")
// Build arguments
buildArgs.addAll(
"--no-fallback",
"-H:+ReportExceptionStackTraces",
"--enable-https",
"-J-Xmx8g"
)
// Quick build mode (faster build, slower runtime — dev only)
quickBuild.set(false)
// Rich output during build
richOutput.set(true)
// Verbose output
verbose.set(true)
// Resource includes
resources {
autodetect()
includedPatterns.add("application.*")
includedPatterns.add("META-INF/.*")
}
}
}
// GraalVM metadata repository
metadataRepository {
enabled.set(true)
version.set("0.3.14")
}
// Toolchain detection
toolchainDetection.set(true)
}
```
### Java Toolchain Configuration
```kotlin
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
graalvmNative {
binaries {
named("main") {
javaLauncher.set(javaToolchains.launcherFor {
languageVersion.set(JavaLanguageVersion.of(21))
vendor.set(JvmVendorSpec.matching("GraalVM Community"))
})
}
}
}
```
## Spring Boot Gradle Integration
For Spring Boot 3.x projects with Gradle:
```kotlin
plugins {
java
id("org.springframework.boot") version "3.4.1"
id("io.spring.dependency-management") version "1.1.7"
id("org.graalvm.buildtools.native") version "0.10.6"
}
// Spring Boot plugin automatically configures AOT processing
// when GraalVM Native Image plugin is detected
```
Build commands:
```bash
# Compile to native executable
./gradlew nativeCompile
# Build OCI image with Cloud Native Buildpacks
./gradlew bootBuildImage
# Run the native executable
./build/native/nativeCompile/<app-name>
# Run AOT processing only
./gradlew processAot
```
### Custom AOT Configuration
```kotlin
tasks.withType<org.springframework.boot.gradle.tasks.aot.ProcessAot>().configureEach {
args("--spring.profiles.active=prod")
}
graalvmNative {
binaries {
named("main") {
buildArgs.addAll(
"--no-fallback",
"-H:+ReportExceptionStackTraces"
)
}
}
}
```
## Testing in Native Mode
Run JUnit tests compiled as a native executable:
```bash
./gradlew nativeTest
```
Configure test binary:
```kotlin
graalvmNative {
binaries {
named("test") {
buildArgs.addAll(
"--no-fallback",
"-H:+ReportExceptionStackTraces"
)
}
}
// Configure test support
testSupport.set(true)
}
```
## Multi-Project Builds
For multi-project Gradle builds, apply the plugin only in the executable subproject:
```kotlin
// settings.gradle.kts
pluginManagement {
plugins {
id("org.graalvm.buildtools.native") version "0.10.6"
}
}
// app/build.gradle.kts (executable subproject)
plugins {
id("org.graalvm.buildtools.native")
}
graalvmNative {
binaries {
named("main") {
imageName.set("my-app")
mainClass.set("com.example.Application")
}
}
}
```
references/maven-native-profile.md
# Maven Native Build Tools Configuration
Complete Maven configuration for building GraalVM native images using the Native Build Tools plugin.
## Table of Contents
1. [Native Profile Setup](#native-profile-setup)
2. [Plugin Configuration Options](#plugin-configuration-options)
3. [Spring Boot Maven Integration](#spring-boot-maven-integration)
4. [Testing in Native Mode](#testing-in-native-mode)
5. [Multi-Module Projects](#multi-module-projects)
---
## Native Profile Setup
Add a `native` profile to your `pom.xml` to keep native-specific configuration separate:
```xml
<profiles>
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.10.6</version>
<extensions>true</extensions>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>compile-no-fork</goal>
</goals>
<phase>package</phase>
</execution>
<execution>
<id>test-native</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
</execution>
</executions>
<configuration>
<imageName>${project.artifactId}</imageName>
<mainClass>${exec.mainClass}</mainClass>
<buildArgs>
<buildArg>--no-fallback</buildArg>
<buildArg>-H:+ReportExceptionStackTraces</buildArg>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
```
## Plugin Configuration Options
### Common Build Arguments
```xml
<configuration>
<imageName>${project.artifactId}</imageName>
<mainClass>com.example.Application</mainClass>
<fallback>false</fallback>
<verbose>true</verbose>
<buildArgs>
<!-- Disable fallback to JVM -->
<buildArg>--no-fallback</buildArg>
<!-- Report exception stack traces -->
<buildArg>-H:+ReportExceptionStackTraces</buildArg>
<!-- Increase build memory -->
<buildArg>-J-Xmx8g</buildArg>
<!-- Enable HTTPS support -->
<buildArg>--enable-https</buildArg>
<!-- Quick build mode (dev only, slower runtime) -->
<buildArg>-Ob</buildArg>
<!-- Include all resources matching pattern -->
<buildArg>-H:IncludeResources=application.*</buildArg>
</buildArgs>
<!-- GraalVM metadata repository support -->
<metadataRepository>
<enabled>true</enabled>
</metadataRepository>
</configuration>
```
### Metadata Repository Integration
The GraalVM Reachability Metadata Repository provides pre-built metadata for popular libraries:
```xml
<configuration>
<metadataRepository>
<enabled>true</enabled>
<version>0.3.14</version>
</metadataRepository>
</configuration>
```
## Spring Boot Maven Integration
For Spring Boot 3.x projects, the parent POM includes a `native` profile. Combine with the Spring Boot Maven Plugin:
```xml
<profiles>
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>process-aot</id>
<goals>
<goal>process-aot</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
</profiles>
```
Build commands:
```bash
# Compile to native executable
./mvnw -Pnative native:compile
# Build OCI image with Cloud Native Buildpacks
./mvnw -Pnative spring-boot:build-image
# Run AOT processing only (for debugging)
./mvnw -Pnative process-aot
```
## Testing in Native Mode
Run JUnit tests compiled as a native executable:
```bash
# Run native tests
./mvnw -Pnative test
# Or explicitly
./mvnw -Pnative native:test
```
Configure test-specific settings:
```xml
<execution>
<id>test-native</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
<configuration>
<buildArgs>
<buildArg>-H:+ReportExceptionStackTraces</buildArg>
<buildArg>--no-fallback</buildArg>
</buildArgs>
</configuration>
</execution>
```
## Multi-Module Projects
For multi-module Maven projects, configure the native plugin in the module that produces the executable:
```xml
<!-- parent pom.xml -->
<pluginManagement>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.10.6</version>
</plugin>
</plugins>
</pluginManagement>
<!-- child module pom.xml (the executable module) -->
<profiles>
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<configuration>
<imageName>${project.artifactId}</imageName>
<mainClass>com.example.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
```
references/quarkus-micronaut-native.md
# Quarkus & Micronaut Native Image Support
Configuration patterns for native-first Java frameworks with GraalVM Native Image.
## Table of Contents
1. [Quarkus Native Build](#quarkus-native-build)
2. [Quarkus Configuration](#quarkus-configuration)
3. [Micronaut Native Build](#micronaut-native-build)
4. [Micronaut Configuration](#micronaut-configuration)
5. [Comparison](#comparison)
---
## Quarkus Native Build
Quarkus is designed native-first and requires minimal GraalVM-specific configuration.
### Building a Native Executable
```bash
# Using Maven (Quarkus Maven plugin handles native build)
./mvnw package -Dnative
# Using Gradle
./gradlew build -Dquarkus.native.enabled=true
# Using Quarkus CLI
quarkus build --native
```
### Container Build (no local GraalVM needed)
```bash
# Build in a container (uses Mandrel/GraalVM image)
./mvnw package -Dnative -Dquarkus.native.container-build=true
# Specify custom builder image
./mvnw package -Dnative \
-Dquarkus.native.container-build=true \
-Dquarkus.native.builder-image=quay.io/quarkus/ubi-quarkus-mandrel-builder-image:jdk-21
```
### Multi-Stage Dockerfile
```dockerfile
FROM quay.io/quarkus/ubi-quarkus-mandrel-builder-image:jdk-21 AS builder
COPY --chown=quarkus:quarkus mvnw /code/mvnw
COPY --chown=quarkus:quarkus .mvn /code/.mvn
COPY --chown=quarkus:quarkus pom.xml /code/
COPY --chown=quarkus:quarkus src /code/src
USER quarkus
WORKDIR /code
RUN ./mvnw package -Dnative -DskipTests
FROM quay.io/quarkus/quarkus-micro-image:2.0
WORKDIR /work/
COPY --from=builder /code/target/*-runner /work/application
RUN chmod 775 /work/application
EXPOSE 8080
CMD ["./application", "-Dquarkus.http.host=0.0.0.0"]
```
## Quarkus Configuration
### application.properties
```properties
# Native image build options
quarkus.native.additional-build-args=--no-fallback,-H:+ReportExceptionStackTraces
# Resource inclusion
quarkus.native.resources.includes=templates/**,META-INF/resources/**
# Enable HTTPS support
quarkus.native.enable-https-url-handler=true
# Build memory
quarkus.native.native-image-xmx=8g
```
### Registering Reflection
Quarkus provides annotations to register classes for reflection:
```java
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public class MyDto {
private String name;
private int age;
// constructors, getters, setters
}
// Register multiple classes including nested types
@RegisterForReflection(targets = {MyDto.class, OrderDto.class},
serialization = true)
public class ReflectionConfig {
}
```
### Testing Native Builds
```java
import io.quarkus.test.junit.QuarkusIntegrationTest;
@QuarkusIntegrationTest
public class NativeMyResourceIT {
@Test
public void testHelloEndpoint() {
given()
.when().get("/hello")
.then()
.statusCode(200)
.body(is("Hello"));
}
}
```
Run native integration tests:
```bash
./mvnw verify -Dnative
```
---
## Micronaut Native Build
Micronaut uses compile-time dependency injection and AOT processing, making it highly compatible with GraalVM.
### Building a Native Executable
```bash
# Using Maven
./mvnw package -Dpackaging=native-image
# Using Gradle
./gradlew nativeCompile
# Using Micronaut CLI
mn create-app --build=gradle --jdk=21 --features=graalvm myapp
```
### Gradle Configuration
```kotlin
plugins {
id("io.micronaut.application") version "4.4.4"
id("org.graalvm.buildtools.native") version "0.10.6"
}
micronaut {
runtime("netty")
testRuntime("junit5")
processing {
incremental(true)
annotations("com.example.*")
}
}
graalvmNative {
binaries {
named("main") {
buildArgs.add("--no-fallback")
}
}
}
```
### Maven Configuration
```xml
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<configFile>aot-${packaging}.properties</configFile>
</configuration>
</plugin>
<profiles>
<profile>
<id>native</id>
<properties>
<packaging>native-image</packaging>
<micronaut.runtime>netty</micronaut.runtime>
</properties>
</profile>
</profiles>
```
## Micronaut Configuration
### Registering Reflection
Micronaut minimizes reflection, but when needed:
```java
import io.micronaut.core.annotation.ReflectiveAccess;
@ReflectiveAccess
public class MyDto {
private String name;
private int age;
}
// Or use @Introspected for bean introspection (preferred)
import io.micronaut.core.annotation.Introspected;
@Introspected
public class MyDto {
private String name;
private int age;
}
```
### Resource Inclusion
In `src/main/resources/META-INF/native-image/resource-config.json`:
```json
{
"resources": {
"includes": [
{"pattern": "application\\.yml"},
{"pattern": "logback\\.xml"},
{"pattern": "META-INF/.*"}
]
}
}
```
### Docker Build
```bash
# Using Micronaut Gradle plugin
./gradlew dockerBuildNative
# Multi-stage Dockerfile
FROM ghcr.io/graalvm/native-image-community:21 AS builder
WORKDIR /app
COPY . .
RUN ./gradlew nativeCompile --no-daemon
FROM debian:bookworm-slim
COPY --from=builder /app/build/native/nativeCompile/myapp /app/myapp
EXPOSE 8080
ENTRYPOINT ["/app/myapp"]
```
---
## Comparison
| Feature | Quarkus | Micronaut |
|---------|---------|-----------|
| DI approach | Build-time with ArC | Compile-time with annotation processors |
| Native build command | `./mvnw package -Dnative` | `./gradlew nativeCompile` |
| Reflection annotation | `@RegisterForReflection` | `@Introspected` / `@ReflectiveAccess` |
| Container build | Built-in container build support | Docker plugin |
| Dev mode | `quarkus dev` (live reload) | `mn run` with restart |
| Startup time (native) | ~10-50ms | ~10-50ms |
| Typical RSS | ~20-50MB | ~20-50MB |
| GraalVM version | Mandrel (Red Hat distribution) | GraalVM CE/EE |
references/reflection-resource-config.md
# GraalVM Reflection & Resource Configuration
Complete guide for GraalVM metadata files that enable reflection, resources, proxies, and serialization in native images.
## Table of Contents
1. [Configuration File Location](#configuration-file-location)
2. [Unified Reachability Metadata](#unified-reachability-metadata)
3. [Reflection Configuration](#reflection-configuration)
4. [Resource Configuration](#resource-configuration)
5. [Proxy Configuration](#proxy-configuration)
6. [Serialization Configuration](#serialization-configuration)
---
## Configuration File Location
Place metadata files in:
```
src/main/resources/
META-INF/native-image/
<group.id>/
<artifact.id>/
reachability-metadata.json # Unified format (recommended)
reflect-config.json # Legacy: reflection only
resource-config.json # Legacy: resources only
proxy-config.json # Legacy: dynamic proxies
serialization-config.json # Legacy: serialization
jni-config.json # Legacy: JNI access
native-image.properties # Build arguments
```
GraalVM automatically discovers files in the `META-INF/native-image/` directory.
## Unified Reachability Metadata
The unified `reachability-metadata.json` format (recommended for GraalVM 23+) combines all metadata:
```json
{
"reflection": [
{
"type": "com.example.dto.UserDto",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"condition": {
"typeReached": "com.example.service.OrderService"
},
"type": "com.example.dto.OrderDto",
"methods": [
{"name": "<init>", "parameterTypes": []},
{"name": "getId", "parameterTypes": []},
{"name": "setId", "parameterTypes": ["java.lang.Long"]}
],
"fields": [
{"name": "id"},
{"name": "status"}
]
}
],
"resources": [
{"glob": "application.yml"},
{"glob": "application-*.yml"},
{"glob": "templates/**/*.html"},
{"glob": "static/**"},
{"glob": "META-INF/services/*"}
],
"bundles": [
{"name": "messages", "locales": ["en", "it", "de"]}
],
"jni": [
{
"type": "com.example.NativeHelper",
"methods": [
{"name": "nativeMethod", "parameterTypes": ["int"]}
]
}
]
}
```
## Reflection Configuration
### Legacy `reflect-config.json`
```json
[
{
"name": "com.example.dto.UserDto",
"allDeclaredConstructors": true,
"allPublicConstructors": true,
"allDeclaredMethods": true,
"allPublicMethods": true,
"allDeclaredFields": true,
"allPublicFields": true
},
{
"name": "com.example.dto.OrderDto",
"methods": [
{"name": "<init>", "parameterTypes": []},
{"name": "<init>", "parameterTypes": ["java.lang.Long", "java.lang.String"]},
{"name": "getId", "parameterTypes": []},
{"name": "setId", "parameterTypes": ["java.lang.Long"]}
],
"fields": [
{"name": "id", "allowWrite": true},
{"name": "status", "allowWrite": true}
]
},
{
"name": "com.example.entity.Product",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true,
"unsafeAllocated": true
}
]
```
### Common Reflection Flags
| Flag | Description |
|------|-------------|
| `allDeclaredConstructors` | Register all constructors (public and private) |
| `allPublicConstructors` | Register only public constructors |
| `allDeclaredMethods` | Register all methods (public and private) |
| `allPublicMethods` | Register only public methods |
| `allDeclaredFields` | Register all fields (public and private) |
| `allPublicFields` | Register only public fields |
| `unsafeAllocated` | Allow `Unsafe.allocateInstance()` |
## Resource Configuration
### Legacy `resource-config.json`
```json
{
"resources": {
"includes": [
{"pattern": "application\\.yml"},
{"pattern": "application-.*\\.yml"},
{"pattern": "logback\\.xml"},
{"pattern": "logback-spring\\.xml"},
{"pattern": "META-INF/services/.*"},
{"pattern": "templates/.*\\.html"},
{"pattern": "static/.*"},
{"pattern": "db/migration/.*\\.sql"}
],
"excludes": [
{"pattern": ".*\\.DS_Store"}
]
},
"bundles": [
{"name": "messages", "locales": ["en", "it"]},
{"name": "ValidationMessages"}
]
}
```
## Proxy Configuration
### Legacy `proxy-config.json`
Register interfaces for JDK dynamic proxy generation:
```json
[
{
"interfaces": [
"com.example.service.UserService",
"org.springframework.aop.SpringProxy",
"org.springframework.aop.framework.Advised",
"org.springframework.core.DecoratingProxy"
]
},
{
"interfaces": [
"com.example.repository.OrderRepository",
"org.springframework.data.repository.Repository"
]
}
]
```
## Serialization Configuration
### Legacy `serialization-config.json`
```json
{
"types": [
{"name": "com.example.dto.UserDto"},
{"name": "com.example.dto.OrderDto"},
{"name": "java.util.ArrayList"},
{"name": "java.util.HashMap"}
],
"lambdaCapturingTypes": [
{"name": "com.example.service.UserService"}
]
}
```
## `native-image.properties`
Configure default build arguments:
```properties
Args = --no-fallback \
-H:+ReportExceptionStackTraces \
--enable-https \
--initialize-at-build-time=org.slf4j
```
references/spring-boot-native.md
# Spring Boot Native Image Support
Complete guide for building Spring Boot 3.x applications as GraalVM native images with AOT processing.
## Table of Contents
1. [Prerequisites](#prerequisites)
2. [AOT Processing](#aot-processing)
3. [RuntimeHints Registration](#runtimehints-registration)
4. [Common Annotations](#common-annotations)
5. [Conditional Beans in Native](#conditional-beans-in-native)
6. [Testing Native Applications](#testing-native-applications)
7. [Cloud Native Buildpacks](#cloud-native-buildpacks)
---
## Prerequisites
- Spring Boot 3.0+ (recommended: 3.4+)
- GraalVM JDK 21+ or GraalVM CE with `native-image` installed
- Native Build Tools plugin (Maven or Gradle)
Spring Boot 3.x provides first-class GraalVM Native Image support. The `spring-boot-starter-parent` includes a `native` profile with all necessary configurations.
## AOT Processing
Spring Boot AOT processing generates optimized code at build time that replaces runtime reflection:
**What AOT does:**
- Evaluates `@Conditional` annotations at build time
- Generates bean definitions as source code
- Creates reflection hints for the remaining dynamic access
- Pre-computes component scanning and auto-configuration
**Important constraints:**
- Bean definitions must be fixed at build time
- `@Profile` conditions are evaluated during AOT — active profiles must be specified at build time
- `@ConditionalOnProperty` is evaluated at build time
- Classpath must remain the same between AOT processing and runtime
### Configuring Active Profiles at Build Time
```xml
<!-- Maven -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>process-aot</id>
<configuration>
<profiles>prod</profiles>
</configuration>
</execution>
</executions>
</plugin>
```
```kotlin
// Gradle
tasks.withType<org.springframework.boot.gradle.tasks.aot.ProcessAot>().configureEach {
args("--spring.profiles.active=prod")
}
```
## RuntimeHints Registration
When Spring Boot's automatic hint detection is insufficient, register hints manually:
### Using `RuntimeHintsRegistrar`
```java
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.context.annotation.ImportRuntimeHints;
@ImportRuntimeHints(MyRuntimeHints.class)
@Configuration
public class AppConfig {
// ...
}
public class MyRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
// Register reflection
hints.reflection()
.registerType(MyDto.class,
builder -> builder
.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.DECLARED_FIELDS));
// Register resources
hints.resources()
.registerPattern("templates/*.html")
.registerPattern("static/**");
// Register serialization
hints.serialization()
.registerType(MySerializableClass.class);
// Register proxies
hints.proxies()
.registerJdkProxy(MyInterface.class);
}
}
```
### Using `@RegisterReflectionForBinding`
A convenience annotation to register reflection hints for DTOs and data classes:
```java
@RestController
@RegisterReflectionForBinding({UserDto.class, OrderDto.class, AddressDto.class})
public class UserController {
@GetMapping("/users/{id}")
public UserDto getUser(@PathVariable Long id) {
return userService.findById(id);
}
}
```
### Using `@Reflective`
Mark individual classes for reflection registration:
```java
@Reflective
public class MyDto {
private String name;
private int age;
// getters, setters, constructors
}
```
## Common Annotations
| Annotation | Purpose |
|-----------|---------|
| `@RegisterReflectionForBinding` | Register DTOs for reflection (constructors, methods, fields) |
| `@Reflective` | Mark a class for reflection registration |
| `@ImportRuntimeHints` | Import a `RuntimeHintsRegistrar` implementation |
| `@AotTestAttributes` | Provide test attributes during AOT processing |
## Conditional Beans in Native
Beans using `@Conditional` annotations are evaluated at build time during AOT:
```java
// This works — condition is resolved at build time
@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public DataSource dataSource() { /* ... */ }
}
// This requires the property to be available at build time
@Configuration
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public class FeatureConfig {
@Bean
public FeatureService featureService() { /* ... */ }
}
```
**Best practice**: For native images, prefer environment variables over properties for runtime-switchable configuration.
## Testing Native Applications
### Native Test Execution
Run JUnit tests in native mode to verify AOT-compiled tests:
```bash
# Maven
./mvnw -Pnative test
# Gradle
./gradlew nativeTest
```
### Test-Specific AOT Processing
```bash
# Maven
./mvnw -Pnative spring-boot:process-test-aot
# Gradle
./gradlew processTestAot
```
### RuntimeHints Testing
Verify that runtime hints are correctly registered without building a native image:
```java
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
@Test
void shouldRegisterHints() {
RuntimeHints hints = new RuntimeHints();
new MyRuntimeHints().registerHints(hints, getClass().getClassLoader());
assertThat(RuntimeHintsPredicates.reflection()
.onType(MyDto.class)
.withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.accepts(hints);
assertThat(RuntimeHintsPredicates.resource()
.forResource("templates/index.html"))
.accepts(hints);
}
```
## Cloud Native Buildpacks
Build OCI images with Paketo Buildpacks (no local GraalVM installation needed):
```bash
# Maven
./mvnw -Pnative spring-boot:build-image \
-Dspring-boot.build-image.imageName=myapp:native
# Gradle
./gradlew bootBuildImage \
--imageName=myapp:native
```
Configure the builder in `pom.xml`:
```xml
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<builder>paketobuildpacks/builder-jammy-tiny:latest</builder>
<env>
<BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
<BP_NATIVE_IMAGE_BUILD_ARGUMENTS>
--no-fallback -H:+ReportExceptionStackTraces
</BP_NATIVE_IMAGE_BUILD_ARGUMENTS>
</env>
</image>
</configuration>
</plugin>
```
references/tracing-agent.md
# GraalVM Tracing Agent
Guide for using the GraalVM tracing agent to automatically collect reachability metadata for native image builds.
## Table of Contents
1. [Overview](#overview)
2. [Running the Tracing Agent](#running-the-tracing-agent)
3. [Agent Modes](#agent-modes)
4. [Integration with Build Tools](#integration-with-build-tools)
5. [Filtering and Fine-Tuning](#filtering-and-fine-tuning)
---
## Overview
The GraalVM tracing agent intercepts all dynamic accesses (reflection, resources, JNI, proxies, serialization) during application execution on the JVM and generates the corresponding GraalVM metadata files.
**When to use the tracing agent:**
- Initial native image migration of a complex project
- After adding new libraries with reflection requirements
- When manual metadata configuration is insufficient
- To discover hidden reflection/resource usage
**Important**: The agent only captures code paths exercised during the run. Ensure thorough coverage by running all application features, endpoints, and edge cases.
## Running the Tracing Agent
### Basic Usage
```bash
# Create output directory
mkdir -p src/main/resources/META-INF/native-image
# Run with the tracing agent
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image \
-jar target/myapp.jar
```
Then exercise all application features (call APIs, trigger scheduled tasks, etc.) before shutting down gracefully.
### With Spring Boot
```bash
# Run Spring Boot app with tracing agent
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image \
-jar target/myapp.jar
# Exercise all endpoints
curl http://localhost:8080/api/users
curl -X POST http://localhost:8080/api/users -H 'Content-Type: application/json' -d '{"name":"test"}'
curl http://localhost:8080/actuator/health
# Shut down gracefully (Ctrl+C or kill -SIGTERM)
```
### Merging with Existing Config
```bash
# Merge agent output with existing metadata (does not overwrite)
java -agentlib:native-image-agent=config-merge-dir=src/main/resources/META-INF/native-image \
-jar target/myapp.jar
```
## Agent Modes
### Output Mode (Fresh Config)
Writes new configuration, overwriting any existing files:
```bash
-agentlib:native-image-agent=config-output-dir=<path>
```
### Merge Mode (Append to Existing)
Merges new entries into existing configuration files:
```bash
-agentlib:native-image-agent=config-merge-dir=<path>
```
### Conditional Mode
Generate conditional metadata (only include if a type is reachable):
```bash
-agentlib:native-image-agent=config-output-dir=<path>,experimental-conditional-config-filter-file=filter.json
```
## Integration with Build Tools
### Maven — Run Agent During Tests
```xml
<profiles>
<profile>
<id>agent</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<configuration>
<agent>
<enabled>true</enabled>
<options>
<option>config-output-dir=src/main/resources/META-INF/native-image</option>
</options>
</agent>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image</argLine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
```
Run with:
```bash
./mvnw -Pagent test
```
### Gradle — Run Agent During Tests
```kotlin
graalvmNative {
agent {
defaultMode.set("standard")
metadataCopy {
inputTaskNames.add("test")
outputDirectories.add("src/main/resources/META-INF/native-image")
mergeWithExisting.set(true)
}
}
}
```
Run with:
```bash
# Run tests with agent
./gradlew -Pagent test
# Copy collected metadata
./gradlew metadataCopy
```
## Filtering and Fine-Tuning
### Agent Filter Configuration
Create a filter file to reduce noise in the generated metadata:
```json
{
"rules": [
{
"excludeClasses": "jdk.internal.**"
},
{
"excludeClasses": "sun.**"
},
{
"excludeClasses": "com.sun.**"
},
{
"includeClasses": "com.example.**"
}
]
}
```
Use with:
```bash
java -agentlib:native-image-agent=config-output-dir=<path>,caller-filter-file=filter.json \
-jar target/myapp.jar
```
### Post-Processing Agent Output
After collecting metadata, review and clean up:
1. **Remove unnecessary entries** — The agent is conservative; many entries may not be needed
2. **Add conditions** — Use `condition.typeReached` to limit when metadata is applied
3. **Verify correctness** — Build the native image and test thoroughly
4. **Commit metadata** — Add the generated files to version control
### Recommended Workflow
```bash
# 1. Run agent with tests for baseline coverage
./mvnw -Pagent test
# 2. Run agent with the full application for runtime coverage
java -agentlib:native-image-agent=config-merge-dir=src/main/resources/META-INF/native-image \
-jar target/myapp.jar
# Exercise all features, then shut down
# 3. Build native image
./mvnw -Pnative package
# 4. Test the native executable
./target/myapp
# 5. If failures occur, repeat steps 2-4 with additional code paths
```
SKILL.md
---
name: graalvm-native-image
description: Provides expert guidance for building GraalVM Native Image executables from Java applications. Use when converting JVM applications to native binaries, optimizing cold start times, reducing memory footprint, configuring native build tools for Maven or Gradle, resolving reflection and resource issues in native builds, or implementing framework-specific native support for Spring Boot, Quarkus, and Micronaut. Triggers include "graalvm native image", "native executable java", "java cold start optimization", "native build tools", "ahead of time compilation java", "reflection config graalvm", "native image build failure".
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---
# GraalVM Native Image for Java Applications
Expert skill for building high-performance native executables from Java applications using GraalVM Native Image, dramatically reducing startup time and memory consumption.
## Overview
GraalVM Native Image compiles Java applications ahead-of-time (AOT) into standalone native executables. These executables start in milliseconds, require significantly less memory than JVM-based deployments, and are ideal for serverless functions, CLI tools, and microservices where fast startup and low resource usage are critical.
This skill provides a structured workflow to migrate JVM applications to native binaries, covering build tool configuration, framework-specific patterns, reflection metadata management, and an iterative approach to resolving native build failures.
## When to Use
Use this skill when:
- Converting a JVM-based Java application to a GraalVM native executable
- Optimizing cold start times for serverless or containerized deployments
- Reducing memory footprint (RSS) of Java microservices
- Configuring Maven or Gradle with GraalVM Native Build Tools
- Resolving `ClassNotFoundException`, `NoSuchMethodException`, or missing resource errors in native builds
- Generating or editing `reflect-config.json`, `resource-config.json`, or other GraalVM metadata files
- Using the GraalVM tracing agent to collect reachability metadata
- Implementing `RuntimeHints` for Spring Boot native support
- Building native images with Quarkus or Micronaut
## Instructions
### 1. Contextual Project Analysis
Before any configuration, analyze the project to determine the build tool, framework, and dependencies:
**Detect the build tool:**
```bash
# Check for Maven
if [ -f "pom.xml" ]; then
echo "Build tool: Maven"
# Check for Maven wrapper
[ -f "mvnw" ] && echo "Maven wrapper available"
fi
# Check for Gradle
if [ -f "build.gradle" ] || [ -f "build.gradle.kts" ]; then
echo "Build tool: Gradle"
[ -f "build.gradle.kts" ] && echo "Kotlin DSL"
[ -f "gradlew" ] && echo "Gradle wrapper available"
fi
```
**Detect the framework by analyzing dependencies:**
- **Spring Boot**: Look for `spring-boot-starter-*` in `pom.xml` or `build.gradle`
- **Quarkus**: Look for `quarkus-*` dependencies
- **Micronaut**: Look for `micronaut-*` dependencies
- **Plain Java**: No framework dependencies detected
**Check the Java version:**
```bash
java -version 2>&1
# GraalVM Native Image requires Java 17+ (recommended: Java 21+)
```
**Identify potential native image challenges:**
- Reflection-heavy libraries (Jackson, Hibernate, JAXB)
- Dynamic proxy usage (JDK proxies, CGLIB)
- Resource bundles and classpath resources
- JNI or native library dependencies
- Serialization requirements
### 2. Build Tool Configuration
Configure the appropriate build tool plugin based on the detected environment.
**For Maven projects**, add a dedicated `native` profile to keep the standard build clean. See the [Maven Native Profile Reference](references/maven-native-profile.md) for full configuration.
Key Maven setup:
```xml
<profiles>
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.10.6</version>
<extensions>true</extensions>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>compile-no-fork</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
<configuration>
<imageName>${project.artifactId}</imageName>
<buildArgs>
<buildArg>--no-fallback</buildArg>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
```
Build with: `./mvnw -Pnative package`
**For Gradle projects**, apply the `org.graalvm.buildtools.native` plugin. See the [Gradle Native Plugin Reference](references/gradle-native-plugin.md) for full configuration.
Key Gradle setup (Kotlin DSL):
```kotlin
plugins {
id("org.graalvm.buildtools.native") version "0.10.6"
}
graalvmNative {
binaries {
named("main") {
imageName.set(project.name)
buildArgs.add("--no-fallback")
}
}
}
```
Build with: `./gradlew nativeCompile`
### 3. Framework-Specific Configuration
Each framework has its own AOT strategy. Apply the correct configuration based on the detected framework.
**Spring Boot** (3.x+): Spring Boot has built-in GraalVM support with AOT processing. See the [Spring Boot Native Reference](references/spring-boot-native.md) for patterns including `RuntimeHints`, `@RegisterReflectionForBinding`, and test support.
Key points:
- Use `spring-boot-starter-parent` 3.x+ which includes the native profile
- Register reflection hints via `RuntimeHintsRegistrar`
- Run AOT processing with `process-aot` goal
- Build with: `./mvnw -Pnative native:compile` or `./gradlew nativeCompile`
**Quarkus and Micronaut**: These frameworks are designed native-first and require minimal additional configuration. See the [Quarkus & Micronaut Reference](references/quarkus-micronaut-native.md).
### 4. GraalVM Reachability Metadata
Native Image uses a closed-world assumption — all code paths must be known at build time. Dynamic features like reflection, resources, and proxies require explicit metadata configuration.
**Metadata files** are placed in `META-INF/native-image/<group.id>/<artifact.id>/`:
| File | Purpose |
|------|---------|
| `reachability-metadata.json` | Unified metadata (reflection, resources, JNI, proxies, bundles, serialization) |
| `reflect-config.json` | Legacy: Reflection registration |
| `resource-config.json` | Legacy: Resource inclusion patterns |
| `proxy-config.json` | Legacy: Dynamic proxy interfaces |
| `serialization-config.json` | Legacy: Serialization registration |
| `jni-config.json` | Legacy: JNI access registration |
See the [Reflection & Resource Config Reference](references/reflection-resource-config.md) for complete format and examples.
### 5. The Iterative Fix Engine
Native image builds often fail due to missing metadata. Follow this iterative approach:
**Step 1 — Execute the native build:**
```bash
# Maven
./mvnw -Pnative package 2>&1 | tee native-build.log
# Gradle
./gradlew nativeCompile 2>&1 | tee native-build.log
```
**Step 2 — Parse build errors and identify the root cause:**
Common error patterns and their fixes:
| Error Pattern | Cause | Fix |
|---------------|-------|-----|
| `ClassNotFoundException: com.example.MyClass` | Missing reflection metadata | Add to `reflect-config.json` or use `@RegisterReflectionForBinding` |
| `NoSuchMethodException` | Method not registered for reflection | Add method to reflection config |
| `MissingResourceException` | Resource not included in native image | Add to `resource-config.json` |
| `Proxy class not found` | Dynamic proxy not registered | Add interface list to `proxy-config.json` |
| `UnsupportedFeatureException: Serialization` | Missing serialization metadata | Add to `serialization-config.json` |
**Step 3 — Apply fixes** by updating the appropriate metadata file or using framework annotations.
**Step 4 — Rebuild and verify.** Repeat until the build succeeds.
**Step 5 — If manual fixes are insufficient**, use the GraalVM tracing agent to collect reachability metadata automatically. See the [Tracing Agent Reference](references/tracing-agent.md).
### 6. Validation and Benchmarking
Once the native build succeeds:
**Verify the executable runs correctly:**
```bash
# Run the native executable
./target/<app-name>
# For Spring Boot, verify the application context loads
curl http://localhost:8080/actuator/health
```
**Measure startup time:**
```bash
# Time the startup
time ./target/<app-name>
# For Spring Boot, check the startup log
./target/<app-name> 2>&1 | grep "Started .* in"
```
**Measure memory footprint (RSS):**
```bash
# On Linux
ps -o rss,vsz,comm -p $(pgrep <app-name>)
# On macOS
ps -o rss,vsz,comm -p $(pgrep <app-name>)
```
**Compare with JVM baseline:**
| Metric | JVM | Native | Improvement |
|--------|-----|--------|-------------|
| Startup time | ~2-5s | ~50-200ms | 10-100x |
| Memory (RSS) | ~200-500MB | ~30-80MB | 3-10x |
| Binary size | JRE + JARs | Single binary | Simplified |
### 7. Docker Integration
Build minimal container images with native executables:
```dockerfile
# Multi-stage build
FROM ghcr.io/graalvm/native-image-community:21 AS builder
WORKDIR /app
COPY . .
RUN ./mvnw -Pnative package -DskipTests
# Minimal runtime image
FROM debian:bookworm-slim
COPY --from=builder /app/target/<app-name> /app/<app-name>
EXPOSE 8080
ENTRYPOINT ["/app/<app-name>"]
```
For Spring Boot applications, use `paketobuildpacks/builder-jammy-tiny` with Cloud Native Buildpacks:
```bash
./mvnw -Pnative spring-boot:build-image
```
## Best Practices
1. **Start with the tracing agent** on complex projects to generate an initial metadata baseline
2. **Use the `native` profile** to keep native-specific config separate from standard builds
3. **Prefer `--no-fallback`** to ensure a true native build (no JVM fallback)
4. **Test with `nativeTest`** to run JUnit tests in native mode
5. **Use GraalVM Reachability Metadata Repository** for third-party library metadata
6. **Minimize reflection** — prefer constructor injection and compile-time DI where possible
7. **Include resource patterns** explicitly rather than relying on classpath scanning
8. **Profile before and after** — always measure startup and memory improvements
9. **Use Java 21+** for the best GraalVM compatibility and performance
10. **Keep GraalVM and Native Build Tools versions aligned**
## Examples
### Example 1: Adding Native Support to a Spring Boot Maven Project
**Scenario:** You have a Spring Boot 3.x REST API and want to compile it to a native executable.
**Step 1 — Add the native profile to `pom.xml`:**
```xml
<profiles>
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>process-aot</id>
<goals>
<goal>process-aot</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
</profiles>
```
**Step 2 — Register reflection hints for DTOs:**
```java
@RestController
@RegisterReflectionForBinding({UserDto.class, OrderDto.class})
public class UserController {
@GetMapping("/users/{id}")
public UserDto getUser(@PathVariable Long id) {
return userService.findById(id);
}
}
```
**Step 3 — Build and run:**
```bash
./mvnw -Pnative native:compile
./target/myapp
# Started MyApplication in 0.089 seconds
```
### Example 2: Resolving a Reflection Error in Native Build
**Scenario:** Native build fails with `ClassNotFoundException` for a Jackson-serialized DTO.
**Error output:**
```
com.oracle.svm.core.jdk.UnsupportedFeatureError:
Reflection registration missing for class com.example.dto.PaymentResponse
```
**Fix — Add to `src/main/resources/META-INF/native-image/reachability-metadata.json`:**
```json
{
"reflection": [
{
"type": "com.example.dto.PaymentResponse",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
}
]
}
```
**Or use the Spring Boot annotation approach:**
```java
@RegisterReflectionForBinding(PaymentResponse.class)
@Service
public class PaymentService { /* ... */ }
```
### Example 3: Using the Tracing Agent for a Complex Project
**Scenario:** A project with many third-party libraries needs comprehensive reachability metadata.
```bash
# 1. Build the JAR
./mvnw package -DskipTests
# 2. Run with the tracing agent
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image \
-jar target/myapp.jar
# 3. Exercise all endpoints
curl http://localhost:8080/api/users
curl -X POST http://localhost:8080/api/orders -H 'Content-Type: application/json' -d '{"item":"test"}'
curl http://localhost:8080/actuator/health
# 4. Stop the application (Ctrl+C), then build native
./mvnw -Pnative native:compile
# 5. Verify
./target/myapp
```
## Constraints and Warnings
### Critical Constraints
- **GraalVM Native Image requires Java 17+** (Java 21+ recommended for best compatibility)
- **Closed-world assumption**: All code paths must be known at build time — dynamic class loading, runtime bytecode generation, and `MethodHandles.Lookup` may not work
- **Build time and memory**: Native compilation is resource-intensive — expect 2-10 minutes and 4-8 GB RAM for typical projects
- **Not all libraries are compatible**: Libraries relying heavily on reflection, dynamic proxies, or CGLIB may require extensive metadata configuration
- **AOT profiles are fixed at build time**: Spring Boot `@Profile` and `@ConditionalOnProperty` are evaluated during AOT processing, not at runtime
### Common Pitfalls
- **Forgetting `--no-fallback`**: Without this flag, the build may silently produce a JVM fallback image instead of a true native executable
- **Incomplete tracing agent coverage**: The agent only captures code paths exercised during the run — ensure all features are tested
- **Version mismatches**: Keep GraalVM JDK, Native Build Tools plugin, and framework versions aligned to avoid incompatibilities
- **Classpath differences**: The classpath at AOT/build time must match runtime — adding/removing JARs after native compilation causes failures
### Security Considerations
- Native executables are harder to decompile than JARs, but are not tamper-proof
- Ensure secrets are not embedded in the native image at build time
- Use environment variables or external config for sensitive data
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Build runs out of memory | Increase build memory: `-J-Xmx8g` in `buildArgs` |
| Build takes too long | Use build cache, reduce classpath, enable quick build mode for dev |
| Application crashes at runtime | Missing reflection/resource metadata — run tracing agent |
| Spring Boot context fails to load | Check `@Conditional` beans and profile-dependent config |
| Third-party library not compatible | Check GraalVM Reachability Metadata repo or add manual hints |