graalvm-native-image by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill graalvm-native-image使用 GraalVM Native Image 从 Java 应用程序构建高性能原生可执行文件的专家技能,可显著降低启动时间和内存消耗。
GraalVM Native Image 将 Java 应用程序提前(AOT)编译为独立的本机可执行文件。这些可执行文件在毫秒级内启动,所需内存远少于基于 JVM 的部署,非常适合对快速启动和低资源消耗有严格要求的无服务器函数、CLI 工具和微服务。
此技能提供了一个结构化的流程,用于将 JVM 应用程序迁移到原生二进制文件,涵盖构建工具配置、特定框架模式、反射元数据管理以及解决原生构建失败的迭代方法。
在以下情况下使用此技能:
ClassNotFoundException、NoSuchMethodException 或资源缺失错误reflect-config.json、resource-config.json 或其他 GraalVM 元数据文件RuntimeHints广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
在进行任何配置之前,分析项目以确定构建工具、框架和依赖项:
检测构建工具:
# 检查 Maven
if [ -f "pom.xml" ]; then
echo "Build tool: Maven"
# 检查 Maven wrapper
[ -f "mvnw" ] && echo "Maven wrapper available"
fi
# 检查 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
通过分析依赖项检测框架:
pom.xml 或 build.gradle 中查找 spring-boot-starter-*quarkus-* 依赖项micronaut-* 依赖项检查 Java 版本:
java -version 2>&1
# GraalVM Native Image 需要 Java 17+(推荐:Java 21+)
识别潜在的原生镜像挑战:
根据检测到的环境配置相应的构建工具插件。
对于 Maven 项目,添加一个专用的 native 配置文件以保持标准构建的简洁。完整配置请参阅 Maven Native Profile Reference。
关键 Maven 设置:
<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>
使用以下命令构建:./mvnw -Pnative package
对于 Gradle 项目,应用 org.graalvm.buildtools.native 插件。完整配置请参阅 Gradle Native Plugin Reference。
关键 Gradle 设置(Kotlin DSL):
plugins {
id("org.graalvm.buildtools.native") version "0.10.6"
}
graalvmNative {
binaries {
named("main") {
imageName.set(project.name)
buildArgs.add("--no-fallback")
}
}
}
使用以下命令构建:./gradlew nativeCompile
每个框架都有自己的 AOT 策略。根据检测到的框架应用正确的配置。
Spring Boot (3.x+):Spring Boot 内置了 GraalVM 支持,并带有 AOT 处理。有关模式(包括 RuntimeHints、@RegisterReflectionForBinding 和测试支持)请参阅 Spring Boot Native Reference。
关键点:
spring-boot-starter-parent 3.x+RuntimeHintsRegistrar 注册反射提示process-aot 目标运行 AOT 处理./mvnw -Pnative native:compile 或 ./gradlew nativeCompileQuarkus 和 Micronaut:这些框架设计为原生优先,需要最少的额外配置。请参阅 Quarkus & Micronaut Reference。
Native Image 使用封闭世界假设 —— 所有代码路径必须在构建时已知。反射、资源和代理等动态功能需要显式的元数据配置。
元数据文件 放置在 META-INF/native-image/<group.id>/<artifact.id>/ 目录下:
| 文件 | 用途 |
|---|---|
reachability-metadata.json | 统一元数据(反射、资源、JNI、代理、包、序列化) |
reflect-config.json | 旧版:反射注册 |
resource-config.json | 旧版:资源包含模式 |
proxy-config.json | 旧版:动态代理接口 |
serialization-config.json | 旧版:序列化注册 |
jni-config.json | 旧版:JNI 访问注册 |
完整格式和示例请参阅 Reflection & Resource Config Reference。
原生镜像构建常常因缺少元数据而失败。请遵循此迭代方法:
步骤 1 — 执行原生构建:
# Maven
./mvnw -Pnative package 2>&1 | tee native-build.log
# Gradle
./gradlew nativeCompile 2>&1 | tee native-build.log
步骤 2 — 解析构建错误并确定根本原因:
常见错误模式及其修复方法:
| 错误模式 | 原因 | 修复方法 |
|---|---|---|
ClassNotFoundException: com.example.MyClass | 缺少反射元数据 | 添加到 reflect-config.json 或使用 @RegisterReflectionForBinding |
NoSuchMethodException | 方法未注册反射 | 将方法添加到反射配置 |
MissingResourceException | 资源未包含在原生镜像中 | 添加到 resource-config.json |
Proxy class not found | 动态代理未注册 | 将接口列表添加到 proxy-config.json |
UnsupportedFeatureException: Serialization | 缺少序列化元数据 | 添加到 serialization-config.json |
步骤 3 — 应用修复,通过更新相应的元数据文件或使用框架注解。
步骤 4 — 重新构建并验证。 重复直到构建成功。
步骤 5 — 如果手动修复不足,使用 GraalVM 追踪代理自动收集可达性元数据。请参阅 Tracing Agent Reference。
原生构建成功后:
验证可执行文件运行正确:
# 运行原生可执行文件
./target/<app-name>
# 对于 Spring Boot,验证应用程序上下文加载
curl http://localhost:8080/actuator/health
测量启动时间:
# 计时启动
time ./target/<app-name>
# 对于 Spring Boot,检查启动日志
./target/<app-name> 2>&1 | grep "Started .* in"
测量内存占用(RSS):
# 在 Linux 上
ps -o rss,vsz,comm -p $(pgrep <app-name>)
# 在 macOS 上
ps -o rss,vsz,comm -p $(pgrep <app-name>)
与 JVM 基线进行比较:
| 指标 | JVM | 原生 | 改进 |
|---|---|---|---|
| 启动时间 | ~2-5s | ~50-200ms | 10-100x |
| 内存(RSS) | ~200-500MB | ~30-80MB | 3-10x |
| 二进制大小 | JRE + JARs | 单个二进制文件 | 简化 |
使用原生可执行文件构建最小的容器镜像:
# 多阶段构建
FROM ghcr.io/graalvm/native-image-community:21 AS builder
WORKDIR /app
COPY . .
RUN ./mvnw -Pnative package -DskipTests
# 最小运行时镜像
FROM debian:bookworm-slim
COPY --from=builder /app/target/<app-name> /app/<app-name>
EXPOSE 8080
ENTRYPOINT ["/app/<app-name>"]
对于 Spring Boot 应用程序,使用带有 Cloud Native Buildpacks 的 paketobuildpacks/builder-jammy-tiny:
./mvnw -Pnative spring-boot:build-image
native 配置文件,将原生特定配置与标准构建分开--no-fallback,以确保真正的原生构建(无 JVM 回退)nativeTest 进行测试,以原生模式运行 JUnit 测试场景: 您有一个 Spring Boot 3.x REST API,希望将其编译为原生可执行文件。
步骤 1 — 将原生配置文件添加到 pom.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>
步骤 2 — 为 DTO 注册反射提示:
@RestController
@RegisterReflectionForBinding({UserDto.class, OrderDto.class})
public class UserController {
@GetMapping("/users/{id}")
public UserDto getUser(@PathVariable Long id) {
return userService.findById(id);
}
}
步骤 3 — 构建并运行:
./mvnw -Pnative native:compile
./target/myapp
# Started MyApplication in 0.089 seconds
场景: 原生构建因 Jackson 序列化的 DTO 出现 ClassNotFoundException 而失败。
错误输出:
com.oracle.svm.core.jdk.UnsupportedFeatureError:
Reflection registration missing for class com.example.dto.PaymentResponse
修复 — 添加到 src/main/resources/META-INF/native-image/reachability-metadata.json:
{
"reflection": [
{
"type": "com.example.dto.PaymentResponse",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
}
]
}
或使用 Spring Boot 注解方法:
@RegisterReflectionForBinding(PaymentResponse.class)
@Service
public class PaymentService { /* ... */ }
场景: 一个包含许多第三方库的项目需要全面的可达性元数据。
# 1. 构建 JAR
./mvnw package -DskipTests
# 2. 使用追踪代理运行
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image \
-jar target/myapp.jar
# 3. 执行所有端点
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. 停止应用程序(Ctrl+C),然后构建原生镜像
./mvnw -Pnative native:compile
# 5. 验证
./target/myapp
MethodHandles.Lookup 可能无法工作@Profile 和 @ConditionalOnProperty 在 AOT 处理期间评估,而不是在运行时--no-fallback:没有此标志,构建可能会静默生成 JVM 回退镜像,而不是真正的原生可执行文件| 问题 | 解决方案 |
|---|---|
| 构建内存不足 | 增加构建内存:在 buildArgs 中使用 -J-Xmx8g |
| 构建时间过长 | 使用构建缓存,减少类路径,为开发启用快速构建模式 |
| 应用程序在运行时崩溃 | 缺少反射/资源元数据 —— 运行追踪代理 |
| Spring Boot 上下文加载失败 | 检查 @Conditional bean 和依赖于配置文件的配置 |
| 第三方库不兼容 | 检查 GraalVM Reachability Metadata 仓库或添加手动提示 |
每周安装量
117
仓库
GitHub Stars
173
首次出现
2026年2月28日
安全审计
安装于
codex103
gemini-cli103
github-copilot100
kimi-cli98
amp98
cline98
Expert skill for building high-performance native executables from Java applications using GraalVM Native Image, dramatically reducing startup time and memory consumption.
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.
Use this skill when:
ClassNotFoundException, NoSuchMethodException, or missing resource errors in native buildsreflect-config.json, resource-config.json, or other GraalVM metadata filesRuntimeHints for Spring Boot native supportBefore any configuration, analyze the project to determine the build tool, framework, and dependencies:
Detect the build tool:
# 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-starter-* in pom.xml or build.gradlequarkus-* dependenciesmicronaut-* dependenciesCheck the Java version:
java -version 2>&1
# GraalVM Native Image requires Java 17+ (recommended: Java 21+)
Identify potential native image challenges:
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 for full configuration.
Key Maven setup:
<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 for full configuration.
Key Gradle setup (Kotlin DSL):
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
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 for patterns including RuntimeHints, @RegisterReflectionForBinding, and test support.
Key points:
spring-boot-starter-parent 3.x+ which includes the native profileRuntimeHintsRegistrarprocess-aot goal./mvnw -Pnative native:compile or ./gradlew nativeCompileQuarkus and Micronaut : These frameworks are designed native-first and require minimal additional configuration. See the Quarkus & Micronaut Reference.
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 |
See the Reflection & Resource Config Reference for complete format and examples.
Native image builds often fail due to missing metadata. Follow this iterative approach:
Step 1 — Execute the native build:
# 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 |
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.
Once the native build succeeds:
Verify the executable runs correctly:
# Run the native executable
./target/<app-name>
# For Spring Boot, verify the application context loads
curl http://localhost:8080/actuator/health
Measure startup time:
# 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):
# 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 |
Build minimal container images with native executables:
# 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:
./mvnw -Pnative spring-boot:build-image
native profile to keep native-specific config separate from standard builds--no-fallback to ensure a true native build (no JVM fallback)nativeTest to run JUnit tests in native modeScenario: You have a Spring Boot 3.x REST API and want to compile it to a native executable.
Step 1 — Add the native profile topom.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:
@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:
./mvnw -Pnative native:compile
./target/myapp
# Started MyApplication in 0.089 seconds
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 tosrc/main/resources/META-INF/native-image/reachability-metadata.json:
{
"reflection": [
{
"type": "com.example.dto.PaymentResponse",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
}
]
}
Or use the Spring Boot annotation approach:
@RegisterReflectionForBinding(PaymentResponse.class)
@Service
public class PaymentService { /* ... */ }
Scenario: A project with many third-party libraries needs comprehensive reachability metadata.
# 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
MethodHandles.Lookup may not work@Profile and @ConditionalOnProperty are evaluated during AOT processing, not at runtime--no-fallback: Without this flag, the build may silently produce a JVM fallback image instead of a true native executable| 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 |
Weekly Installs
117
Repository
GitHub Stars
173
First Seen
Feb 28, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex103
gemini-cli103
github-copilot100
kimi-cli98
amp98
cline98
Flutter应用架构设计指南:分层结构、数据层实现与最佳实践
4,500 周安装
股票行情实时查询工具 - 获取股价、成交量、市值、移动平均线等数据
337 周安装
小红书内容转换器:一键将通用文章转为小红书爆款笔记格式 | AI写作助手
336 周安装
反重力工作流技能:自动化多阶段任务编排,实现SaaS发布、安全审计、AI系统构建
346 周安装
增长循环设计指南:5种产品主导增长机制,构建可持续用户增长飞轮
344 周安装
agent-skill-creator:AI智能体技能自动化生成工厂,无需代码创建跨平台技能
345 周安装
workflow-init:Vercel Workflow DevKit 自动化初始化工具,支持 Next.js/Nuxt/SvelteKit 等主流框架
358 周安装
| Legacy: JNI access registration |
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 |