Security review
No findings observed7 of 7 catalog files reviewed · (UTC)
Review details
AI instruction review via GitHub Agentic Workflows. Reviews inspect a recorded catalog snapshot; they do not execute skill files. AI can miss risks or report false positives.
Coverage is limited to catalog files. External links and upstream files absent from the catalog were not inspected.
Reviewed files (7)
SKILL.mdreferences/build-tools.mdreferences/micronaut.mdreferences/quarkus.mdreferences/reachability-metadata.mdreferences/spring-boot.mdreferences/troubleshooting.md
Usage example
A Spring Boot app needs a GraalVM native executable.
Try a prompt like this
Add GraalVM Native Image support to this Spring Boot project. Inspect its build tool, diagnose native build errors, and verify the resulting executable if the environment supports it.
Illustrative request, not an executed example or a guarantee of activation or results. Adapt it to your task after reviewing the skill’s instructions, prerequisites, and security review. Tool access and permissions depend on your setup.
Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install java-add-graalvm-native-image-support@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin java-add-graalvm-native-image-support v1.0.0 follows the Agent Plugins spec.
gh skills-hub install java-add-graalvm-native-image-support Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/java-add-graalvm-native-image-support/ Extract the ZIP to .github/skills/ in your repo. The folder name must match java-add-graalvm-native-image-support for Copilot to auto-discover it.
Skill Files (7)
SKILL.md 9.0 KB
---
name: java-add-graalvm-native-image-support
description: 'GraalVM Native Image skill for Spring Boot, Micronaut and plain Java: detects the build tool and framework, adds native image support, builds the executable, analyzes errors, and iterates until the native build succeeds and the binary runs correctly. For Quarkus projects it only dispatches to the quarkus-native-and-container skill.'
---
# GraalVM Native Image Support
Single source of truth for adding GraalVM Native Image to a Java project, whatever the framework. Work iteratively: configure, build, read the error, fix, rebuild, until the native build succeeds and the executable runs correctly.
Detail lives in `references/`; load only what the project needs:
| Topic | File |
|---|---|
| Maven / Gradle native plugin setup | [references/build-tools.md](references/build-tools.md) |
| Reachability metadata and tracing agent | [references/reachability-metadata.md](references/reachability-metadata.md) |
| Common build/runtime errors and fixes | [references/troubleshooting.md](references/troubleshooting.md) |
| Spring Boot (AOT, `-Pnative`, `nativeCompile`, `build-image`) | [references/spring-boot.md](references/spring-boot.md) |
| Quarkus | `quarkus-native-and-container` skill (hand off); short pointer in [references/quarkus.md](references/quarkus.md) |
| Micronaut | [references/micronaut.md](references/micronaut.md) |
## Step 1: Analyze the project
1. Build tool: `pom.xml` (Maven) or `build.gradle` / `build.gradle.kts` (Gradle). Prefer the wrapper (`./mvnw`, `./gradlew`) when present.
2. Framework, from dependencies/plugins:
- Spring Boot: `spring-boot-starter-parent`, `spring-boot-maven-plugin`, or `org.springframework.boot` Gradle plugin
- Quarkus: `io.quarkus` BOM/plugin or `quarkus-*` dependencies
- Micronaut: `io.micronaut` parent/plugin or `micronaut-*` dependencies
- otherwise plain Java
3. Existing native configuration: native-build-tools plugin, `META-INF/native-image/`, native profile, `application.properties` native keys.
4. Toolchain: run `java -version` and `native-image --version`. Local native compilation needs a GraalVM JDK (with `native-image`) as the JDK used for the build. Container or buildpack builds (Spring Boot buildpacks via `bootBuildImage`/`spring-boot:build-image`, Quarkus container builds) compile inside a container and need no local GraalVM, only a container runtime. Check the project's Java level against the installed GraalVM version.
If the framework is Quarkus, stop here and hand off to the `quarkus-native-and-container` skill. Container builds there need no local GraalVM.
## Scope and JVM baseline
- Adding native support does not authorize a JDK, framework, library, build-tool, or wrapper upgrade. Preserve the existing BOM/parent-managed versions and test conventions; ask before changing versions to solve native compatibility.
- Run the project's existing JVM build and tests before editing. Record pre-existing failures rather than weakening checks to hide them. Keep the JVM packaging/run path working alongside native support.
- After any approved dependency or framework change, rerun that JVM baseline before continuing with native builds. Verify the same relevant behavior on both JVM and native paths.
- Ask before creating or changing CI workflows, adding native CI jobs, or changing runner resources. Suggest commands separately if CI changes were not requested.
## Step 2: Get a GraalVM toolchain
- **Oracle GraalVM** (free under the GraalVM Free Terms and Conditions) and **GraalVM Community Edition** builds provide `native-image`. Use a release matching the project's Java version (for example, GraalVM for JDK 21 or newer; Spring Boot 3.x/4.x need a Java 17+ baseline, see the Spring reference).
- Install with SDKMAN (`sdk list java`, then `sdk install java <identifier>` using an identifier from that list), a vendor download, or a CI action such as `graalvm/setup-graalvm`. Pick the version from the vendor's current download page rather than hard-coding one.
- Linux needs a C toolchain and zlib headers (`build-essential`, `zlib1g-dev`); macOS needs Xcode command line tools; Windows needs Visual Studio Build Tools. Check the current GraalVM "Native Image prerequisites" page.
## Step 3: Add native support
Per framework:
- **Spring Boot**: with Maven, `spring-boot-starter-parent` only manages the native plugins' versions and configuration in its `native` profile, so declare `native-maven-plugin` and `spring-boot-maven-plugin` in `<build><plugins>` if missing (no versions needed); with Gradle, apply `org.graalvm.buildtools.native` next to `org.springframework.boot`; a custom parent needs the plugin added by hand. Do not duplicate configuration the parent already provides. See [references/spring-boot.md](references/spring-boot.md).
- **Quarkus**: hand off to the `quarkus-native-and-container` skill.
- **Micronaut**: built in via the Micronaut build plugins. See [references/micronaut.md](references/micronaut.md).
- **Plain Java** (or any project without a framework plugin): add the GraalVM Native Build Tools plugin. See [references/build-tools.md](references/build-tools.md). Resolve the plugin version at run time from Maven Central (`org.graalvm.buildtools:native-maven-plugin`) or the Gradle Plugin Portal (`org.graalvm.buildtools.native`) and pin it in the build file; do not copy a version from memory.
## Step 4: Build
| Setup | Command |
|---|---|
| Plain Maven | `./mvnw -Pnative native:compile` |
| Plain Gradle | `./gradlew nativeCompile` |
| Spring Boot Maven | `./mvnw -Pnative native:compile` (or `spring-boot:build-image` for a container) |
| Spring Boot Gradle | `./gradlew nativeCompile` (or `bootBuildImage`) |
| Micronaut Maven | `./mvnw package -Dpackaging=native-image` |
| Micronaut Gradle | `./gradlew nativeCompile` |
Native builds are slow and memory hungry (several GB of RAM). Capture the full output to inspect it.
## Step 5: Iterate until the build succeeds
1. Read the first real error, not the final summary.
2. Match it against [references/troubleshooting.md](references/troubleshooting.md).
3. Apply the smallest fix, in this order of preference:
1. Check whether a compatible library/framework version has built-in native support (see the [reachability metadata repository](https://github.com/oracle/graalvm-reachability-metadata)). Propose the upgrade; apply it only with user approval and rerun the JVM baseline. If declined, try metadata or framework hints compatible with the current versions.
2. Use the framework's own mechanism (Spring `RuntimeHints`, Quarkus `@RegisterForReflection`, Micronaut `@Introspected`).
3. Collect metadata with the tracing agent (see [references/reachability-metadata.md](references/reachability-metadata.md)).
4. Hand-write metadata under `src/main/resources/META-INF/native-image/<groupId>/<artifactId>/`.
5. Adjust initialization (`--initialize-at-build-time` / `--initialize-at-run-time`) only for specific classes.
4. Rebuild. Repeat until the build completes with no errors.
## Step 6: Verify the executable
A successful build is not enough: many problems only appear at runtime.
- Run the binary and exercise the main paths (HTTP endpoints, DB access, serialization, resource loading, scheduled jobs).
- Run the native tests where the framework supports them (`native:test`, `nativeTest`, Quarkus `@QuarkusIntegrationTest`).
- Compare startup time and memory against the JVM run only if the user asks for it.
- Report the exact commands run, whether the build and the run succeeded, and any remaining warnings.
## Pitfalls
- Recommend a native build and native test run in CI with an explicit GraalVM version; add or change CI only with user consent.
- Mockito's default inline mock maker does not work on native image (Mockito 5.0.0 release notes); use the subclass mock maker for native tests.
- Do not leave `--report-unsupported-elements-at-runtime` or verbose flags in production builds unless justified.
## References
- [GraalVM Native Image documentation](https://www.graalvm.org/latest/reference-manual/native-image/)
- [Native Build Tools](https://graalvm.github.io/native-build-tools/latest/index.html)
- [GraalVM reachability metadata repository](https://github.com/oracle/graalvm-reachability-metadata)
- [Spring Boot GraalVM native images](https://docs.spring.io/spring-boot/reference/packaging/native-image/index.html)
- [Quarkus building a native executable](https://quarkus.io/guides/building-native-image)
- [Micronaut GraalVM guide](https://docs.micronaut.io/latest/guide/#graal)
## Upstream sources (read before upgrading GraalVM or native config)
Fetch the page for the target version; prefer it over this skill when they conflict.
- GraalVM release notes: <https://www.graalvm.org/release-notes/>
- Reachability metadata format: <https://www.graalvm.org/latest/reference-manual/native-image/metadata/>
- Build configuration options: <https://www.graalvm.org/latest/reference-manual/native-image/overview/BuildConfiguration/>
- Metadata repository (check your library versions are covered): <https://github.com/oracle/graalvm-reachability-metadata>
build-tools.md 4.2 KB
# Build tool setup (Maven and Gradle)
Use the GraalVM Native Build Tools plugin for plain Java projects. Quarkus and Micronaut projects get native support (or an equivalent) from their own plugins; do not add it again there. Spring Boot with Maven and `spring-boot-starter-parent` inherits its version and configuration through the parent's `native` profile (`pluginManagement`), but you must still declare `native-maven-plugin` and `spring-boot-maven-plugin` in `<build><plugins>` if absent (no version needed); Spring Boot with Gradle, or Maven with a custom parent, needs the plugin applied explicitly (see `spring-boot.md`).
## Versions
Do not hard-code a version from memory. Resolve the current release at run time and pin it:
- Maven Central: `org.graalvm.buildtools:native-maven-plugin` (search.maven.org or `https://repo.maven.apache.org/maven2/org/graalvm/buildtools/native-maven-plugin/maven-metadata.xml`)
- Gradle Plugin Portal: `org.graalvm.buildtools.native`
- Release notes: https://graalvm.github.io/native-build-tools/latest/index.html
Below, `NBT_VERSION` stands for the version you resolved. Replace it with the real number in the file.
## Maven
Put it in a `native` profile so normal builds are unaffected:
```xml
<profiles>
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>NBT_VERSION</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>com.example.Main</mainClass>
<buildArgs>
<buildArg>--no-fallback</buildArg>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
```
Set `mainClass` to the project's real entry point (or rely on the jar plugin's configured main class). Build: `./mvnw -Pnative native:compile`; run tests natively: `./mvnw -Pnative test`. The executable lands in `target/`.
## Gradle
Groovy DSL:
```groovy
plugins {
id 'application'
id 'org.graalvm.buildtools.native' version 'NBT_VERSION'
}
graalvmNative {
binaries {
main {
imageName = project.name
mainClass = application.mainClass
buildArgs.add('--no-fallback')
}
}
}
```
Kotlin DSL:
```kotlin
plugins {
application
id("org.graalvm.buildtools.native") version "NBT_VERSION"
}
graalvmNative {
binaries {
named("main") {
imageName.set(project.name)
mainClass.set(application.mainClass)
buildArgs.add("--no-fallback")
}
}
}
```
Build: `./gradlew nativeCompile`; run: `./gradlew nativeRun`; test: `./gradlew nativeTest`. The executable lands in `build/native/nativeCompile/`.
Gradle toolchains: to select GraalVM via a toolchain, set `javaLauncher` in `graalvmNative.binaries.main` using `javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(<java-version>); vendor = JvmVendorSpec.GRAAL_VM }`. Otherwise make sure `JAVA_HOME` points to a GraalVM JDK.
## `--no-fallback`
Fallback images (which bundle a JVM launcher) are deprecated and removed in recent GraalVM releases, so the flag is the default behavior there. Keep it for older toolchains so failures are not hidden.
## Useful build arguments
| Argument | Purpose |
|---|---|
| `-Ob` | quick build mode for development |
| `--initialize-at-run-time=<class-or-package>` | defer class initialization |
| `--initialize-at-build-time=<class-or-package>` | initialize during the build (only when safe) |
| `-H:+ReportExceptionStackTraces` | fuller build errors |
| `--gc=G1` | G1 GC (Linux, Oracle GraalVM) for throughput; default serial GC |
| `-march=native` | tune for the build CPU only; avoid for distributed binaries (use `-march=compatibility`) |
micronaut.md 2.6 KB
# Micronaut native images
Micronaut performs ahead-of-time processing at compile time, so most native image metadata is generated automatically.
## Commands
- Maven: `./mvnw package -Dpackaging=native-image` (container build: `./mvnw package -Dpackaging=docker-native`)
- Gradle: `./gradlew nativeCompile` (container: `./gradlew dockerBuildNative`)
- Native tests: `./mvnw -Pnative test` or `./gradlew nativeTest`, depending on the generated project
Check the generated project's profiles/tasks and use a compatible GraalVM JDK. In the standard Micronaut parent POM (4.10.0 and 5.0.2), `graalvm` configures annotation processing; `native` binds the Native Build Tools native-test goals. A successful `-Pgraalvm test` alone is not evidence that native tests ran.
The Micronaut Maven/Gradle plugins configure the Native Build Tools plugin for you; do not add it again.
## Reflection and resources
1. **Bean introspection**: `@Introspected` for POJOs avoids reflection:
```java
@Introspected
public class MyDto {
private String name;
private int value;
// getters and setters
}
```
Or `@Serdeable` for Micronaut Serialization types.
2. **Reflection**: `@ReflectionConfig(type = MyClass.class, accessType = TypeHint.AccessType.ALL_DECLARED_CONSTRUCTORS)` (both from `io.micronaut.core.annotation`; `accessType` takes `TypeHint.AccessType[]`) on a configuration class, or `@TypeHint(MyClass.class)` for the default access.
3. **Resources**: Micronaut has no resource annotation; list patterns in `META-INF/native-image/<group>/<artifact>/resource-config.json` (or the unified `reachability-metadata.json`), or use the Native Build Tools resource detection settings.
4. **Gradle build arguments** (only if needed):
```groovy
graalvmNative {
binaries {
main {
buildArgs.add("--initialize-at-run-time=io.netty")
}
}
}
```
Micronaut already sets sensible initialization defaults; add flags only for a specific failing class. Avoid `--report-unsupported-elements-at-runtime` outside diagnosis.
## Tips
- Use Micronaut's compile-time features (`@Introspected`, `@Serdeable`, `@Client` interfaces) rather than runtime reflection.
- Netty and HTTP client tuning is a runtime concern; do not change `netty.default.allocator` settings to fix native build errors.
- Check whether a compatible Micronaut module update supplies metadata before adding it manually; propose any upgrade for user approval, preserve managed versions, and rerun the JVM baseline afterwards.
Guide: https://docs.micronaut.io/latest/guide/#graal
quarkus.md 0.5 KB
# Quarkus native images
Quarkus is handled by the `quarkus-native-and-container` skill, which is the source of truth for native builds, container-image builds and Kubernetes manifests. Hand off to it after framework detection.
- Native support is built into Quarkus; do not add the Native Build Tools plugin.
- Container builds (`-Dquarkus.native.container-build=true`) need no local GraalVM or Mandrel, only Docker or Podman.
- If the `quarkus-native-and-container` skill is not installed, see https://quarkus.io/guides/building-native-image.
reachability-metadata.md 5.9 KB
# Reachability metadata and the tracing agent
Native Image only includes what it can see statically. Anything reached dynamically (reflection, resources, JNI, dynamic proxies, serialization) must be described by *reachability metadata*.
## Where metadata lives
`src/main/resources/META-INF/native-image/<groupId>/<artifactId>/` in your project (the `<groupId>/<artifactId>` subfolder avoids clashes between jars). Two formats exist:
- Legacy per-feature files: `reflect-config.json`, `resource-config.json`, `jni-config.json`, `proxy-config.json`, `serialization-config.json`.
- Unified `reachability-metadata.json` (introduced in GraalVM for JDK 23 and used by newer releases). The unified format is preferred for new metadata and supports newer capabilities, but Native Image still discovers legacy files under `META-INF/native-image`, so do not discard valid existing configuration. Check the GraalVM documentation for your version and prefer regenerating metadata with the tracing agent of the toolchain you use.
Libraries often publish metadata themselves, and the community [GraalVM reachability metadata repository](https://github.com/oracle/graalvm-reachability-metadata) covers many popular ones. The Native Build Tools plugin pulls it automatically when enabled (`metadataRepository` in Gradle, default for recent plugin versions in Maven). Check existing metadata first; if an upgrade would help, propose it for user approval and rerun the JVM baseline after the change. Otherwise collect or write metadata for the current version.
## Tracing agent
Run the app on the JVM with the agent while exercising every code path, and the agent writes the metadata.
Direct:
```sh
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image/<groupId>/<artifactId> -jar target/app.jar
```
Via the build tool (preferred):
```sh
./mvnw -Pnative -Dagent=true -DskipNativeTests=true test # collect test-stage metadata on the JVM
./gradlew -Pagent test # agent during tests, Gradle
./gradlew -Pagent run
./gradlew metadataCopy --task test --dir src/main/resources/META-INF/native-image/<groupId>/<artifactId>
```
The Maven example assumes the plain-Java `native` profile in [build-tools.md](build-tools.md), which also binds `native:test` to the test phase. Check the actual project's profile bindings: Spring Boot uses a separate `nativeTest` profile (see [spring-boot.md](spring-boot.md)). Use `-DskipNativeTests=true` for metadata collection so JVM tests still execute with the tracing agent, without compiling or running native test binaries. Do not use `-DskipTests` or `-Dmaven.test.skip`: those skip the JVM tests needed to exercise the agent.
The Maven agent writes to `target/native/agent-output/{test,main}`. Review the files for noise, then configure [metadata copying](https://graalvm.github.io/native-build-tools/latest/maven-plugin.html#metadata-copy) inside the Native Build Tools plugin so the approved output survives `clean` and is included in the native build:
```xml
<configuration>
<!-- Keep any existing Native Build Tools configuration here. -->
<agent>
<metadataCopy>
<!-- For the JVM test command above, skip the main stage that was not run. -->
<disabledStages>
<stage>main</stage>
</disabledStages>
<merge>true</merge>
<outputDirectory>${project.basedir}/src/main/resources/META-INF/native-image/${project.groupId}/${project.artifactId}</outputDirectory>
</metadataCopy>
</agent>
</configuration>
```
After reviewing the test-stage output, persist it with:
```sh
./mvnw -Pnative -Dagent=true native:metadata-copy
```
If you collected only the application (`main`) stage, disable `test` instead; configure `disabledStages` for every stage you did not collect. `merge=true` merges with existing metadata when the destination has a complete metadata set (unified `reachability-metadata.json` or all four legacy files); otherwise merge or reconcile existing partial files manually before copying, so valid metadata is not discarded. Run native tests afterwards with the project's appropriate profile and without `-DskipNativeTests=true`; the metadata-collection run is not evidence that native tests passed.
For a manual application run, configure the `exec-maven-plugin` execution described in the Native Build Tools [Maven agent guide](https://graalvm.github.io/native-build-tools/latest/maven-plugin.html#agent-support-running-application), then run it with:
```sh
./mvnw -Pnative -Dagent=true -DskipTests -DskipNativeBuild=true package exec:exec@java-agent
```
Copy the collected `main` stage as above, disabling the uncollected `test` stage.
See the Native Build Tools "Agent Support" page for the exact setup for your plugin version.
Tips:
- Exercise every endpoint, serialization path and resource load; unexercised paths are not captured.
- Review the generated files and delete noise (test-only classes).
- Merge repeated runs with `native-image-configure` or the agent's merge mode (`config-merge-dir=`).
- Re-run the agent after changing dependencies.
## Hand-written examples (legacy format)
Reflection (`reflect-config.json`):
```json
[
{
"name": "com.example.YourClass",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
}
]
```
Resources (`resource-config.json`):
```json
{
"resources": {
"includes": [
{"pattern": "\\Qapplication.properties\\E"},
{"pattern": ".*\\.ya?ml"}
]
}
}
```
JNI (`jni-config.json`):
```json
[
{
"name": "com.example.NativeClass",
"methods": [
{"name": "nativeMethod", "parameterTypes": ["java.lang.String"]}
]
}
]
```
Dynamic proxies (`proxy-config.json`):
```json
[
["com.example.Interface1", "com.example.Interface2"]
]
```
Frameworks offer typed alternatives (Spring `RuntimeHints`, Quarkus `@RegisterForReflection`, Micronaut `@Introspected`); prefer them to raw JSON in framework projects.
spring-boot.md 5.8 KB
# Spring Boot native images
Spring Boot 3.x and later supports GraalVM native images through Spring AOT. Check the Spring Boot version in the build: 3.x needs Java 17+ and a GraalVM matching the Spring Boot docs for that release; always confirm the exact supported GraalVM version in the reference docs for your Spring Boot version (https://docs.spring.io/spring-boot/reference/packaging/native-image/index.html).
## How it works
- The Spring Boot Maven plugin / Gradle plugin run **AOT processing** at build time, generating bean definitions and runtime hints.
- `spring-boot-starter-parent` defines a `native` profile that configures `native-maven-plugin` and `spring-boot-maven-plugin` (the `process-aot` execution) only in `pluginManagement`, so versions and configuration are inherited but the plugins are not applied. Projects created with start.spring.io already declare both in `<build><plugins>`; for an existing project lacking `org.graalvm.buildtools:native-maven-plugin`, declare it and `spring-boot-maven-plugin` without versions or configuration. Verified in the `spring-boot-starter-parent` 3.5.0 POM.
- With Gradle, applying the `org.graalvm.buildtools.native` plugin next to `org.springframework.boot` activates AOT tasks (`processAot`, `processTestAot`).
- Without the Spring parent (custom parent / BOM import), add the Native Build Tools plugin yourself, following `build-tools.md`, and declare `process-aot` for the Spring Boot plugin.
## Commands
| Goal | Maven | Gradle |
|---|---|---|
| Native executable | `./mvnw -Pnative native:compile` | `./gradlew nativeCompile` |
| Native container image (Cloud Native Buildpacks, needs Docker) | `./mvnw -Pnative spring-boot:build-image` | `./gradlew bootBuildImage` |
| Native tests | `./mvnw -PnativeTest test` | `./gradlew nativeTest` |
| Run AOT on the JVM to debug | `./mvnw spring-boot:process-aot` then run with `-Dspring.aot.enabled=true` | `./gradlew processAot` |
Note that `build-image` with buildpacks does not require a local GraalVM: the builder provides it. Set `BP_NATIVE_IMAGE_BUILD_ARGUMENTS` / `BP_JVM_VERSION` through the plugin's `<environment>` / `bootBuildImage { environment }` when you need extra arguments.
Verified on Boot 4.1.1 with Oracle GraalVM 25.0.4 (arm64, web + actuator + validation): `./mvnw -Pnative native:compile` (no prior `package` needed) takes about 2m40 and `./gradlew nativeCompile` about 3m50, both give a 102 MB binary that starts in 0.07-0.23 s with about 80 MB RSS. The Gradle toolchain must point at the GraalVM JDK (`-Dorg.gradle.java.installations.paths=<graalvm home>` if it is not auto-detected). Gradle `bootBuildImage` (Boot enables native when `org.graalvm.buildtools.native` is applied; set `environment = ['BP_JVM_VERSION': '25']` if no matching toolchain) also built a working image and started in 0.1-0.2 s with native-build-tools 1.1.7 and 1.1.8. A one-off `Invalid logger interface ...hibernate.validator...Log (implementation not found)` crash matches [native-build-tools#1017](https://github.com/graalvm/native-build-tools/issues/1017) (hibernate-validator reachability metadata overwritten by the jboss-logging one in the jar); not reproduced, so check that `META-INF/native-image/org.hibernate.validator/*/reachability-metadata.json` in the jar is large (about 150 KB), update the plugin, and run the image and hit `/actuator/health` before trusting it.
Check `spring.aot.enabled=true` on the JVM first: it surfaces most AOT problems faster than a full native build.
## Custom runtime hints
Only when libraries or your own code use reflection, resources or serialization that AOT cannot infer:
```java
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
public class MyRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerType(MyClass.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS);
hints.resources().registerPattern("custom-config/*.properties");
hints.serialization().registerType(MySerializableClass.class);
}
}
```
```java
@SpringBootApplication
@ImportRuntimeHints(MyRuntimeHints.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
Alternatives: `@RegisterReflectionForBinding(MyDto.class)` on a bean or configuration class for DTOs bound by Jackson, and `@Reflective` on custom annotations. Test hints with `RuntimeHintsPredicates`.
## Common issues
1. **Jackson DTOs / mix-ins**: register the types with `@RegisterReflectionForBinding` or `hints.reflection()`; include mix-in classes. Records usually work without extra hints.
2. **Resources**: register non-standard resource patterns (`hints.resources().registerPattern(...)`). `application.properties`/`application.yml` are handled.
3. **Logback**: Spring's AOT supports standard Logback configs (`logback-spring.xml`). Custom Logback components may need reflection hints.
4. **Conditional beans**: `@Profile`, `@ConditionalOnProperty` and similar are evaluated at **build time** in AOT. Properties that change bean structure must be fixed when building; runtime overrides will not add or remove beans.
5. **Dynamic proxies / CGLIB**: handled by AOT for Spring components; third-party proxies need `proxy-config` hints.
6. **Libraries without metadata**: check for a compatible update, but obtain user approval before upgrading and rerun the JVM baseline afterwards. If staying on current versions, use the tracing agent (see `reachability-metadata.md`).
7. **Testcontainers / test slices** in native tests: follow the Spring Boot reference for native testing; some tests are not supported natively.
troubleshooting.md 3.3 KB
# Common native image errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `ClassNotFoundException`, `NoSuchMethodException`, `NoSuchFieldException` at runtime | missing reflection metadata | tracing agent; framework hints; `reflect-config.json` |
| `MissingReflectionRegistrationError` | same, reported precisely | register the named type/member |
| Resource `null` / `FileNotFoundException` for classpath files | resource not included | `resource-config.json` pattern; framework resource setting |
| `Proxy class defined by interfaces [...] not found` | missing proxy metadata | `proxy-config.json` / framework hints |
| `Classes that should be initialized at run time got initialized during image building` | build-time init of a class holding runtime state (random, sockets, threads, system properties) | `--initialize-at-run-time=<class>` |
| `Object of type X was found in the image heap` (random, threads, file handles) | build-time init stored non-image-safe state | move init to run time for the owning class |
| `Detected a started Thread in the image heap` | thread started in a static initializer | defer to run time |
| `UnsatisfiedLinkError` | missing JNI/native lib | `jni-config.json`; ship or link the native library |
| `Unsupported features in ...` / `Discovered unresolved type during parsing` | an optional dependency is missing or the library is unsupported | add the dependency; upgrade the library; check the reachability metadata repository |
| Serialization errors (`java.io.Serializable`) | missing serialization metadata | `serialization-config.json` / framework hints |
| Out of memory during build | native build needs several GB | raise container/CI memory; `-J-Xmx<size>` as a build arg; close other processes |
| Build very slow | normal for full optimization | `-O b` for dev only; use CI caching; build only in a profile |
| Binary behaves differently from JVM | build-time initialization, missing metadata, no dynamic class loading | native tests; tracing agent over the full test suite |
| Large binary | many dependencies | review dependencies; `-Os`; on Oracle GraalVM check `--emit build-report` (not available in Community Edition) |
| Dynamic class loading, `Class.forName` on unknown names, agents, `MethodHandles` tricks | not supported in native images | refactor to static registration |
## Diagnosis workflow
1. Run the build with `-H:+ReportExceptionStackTraces` for the full error.
2. On Oracle GraalVM, add `--emit build-report` to see what pulled classes in (Build Report is not available in GraalVM Community Edition; use the standard build output there).
3. For runtime errors, run the same scenario with the tracing agent on the JVM and diff the output against your metadata.
4. On Oracle GraalVM, use the build report to find which dependency causes the size or initialization problem.
## Cautions
- Dependency/framework upgrades and CI or runner changes require user approval even when suggested above; preserve managed versions and rerun the JVM baseline after dependency changes.
- `--initialize-at-build-time` is an optimization with risks; apply it to named classes, not broad packages, unless the framework documents it.
- `--report-unsupported-elements-at-runtime` only delays failures; use it for diagnosis, not as a fix.
- Native binaries are platform-specific; build on the target OS/architecture (or in a matching container).
License (MIT)
View full license text
MIT License Copyright GitHub, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.