graalvm-native-image

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GraalVM Native Image for Java Applications

面向Java应用的GraalVM Native Image

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将Java应用构建为高性能原生可执行文件的专业技能,可大幅缩短启动时间、降低内存消耗。

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.
GraalVM Native Image采用提前编译(AOT)模式将Java应用编译为独立的原生可执行文件。这类可执行文件启动仅需数毫秒,相比基于JVM部署的方案内存占用显著更低,非常适合对启动速度、低资源消耗有严苛要求的Serverless函数、CLI工具、微服务场景。
本技能提供了将JVM应用迁移为原生二进制文件的结构化工作流,覆盖构建工具配置、框架专属适配方案、反射元数据管理,以及迭代解决原生构建故障的方法。

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
在以下场景中可使用本技能:
  • 将基于JVM的Java应用转换为GraalVM原生可执行文件
  • 优化Serverless或容器化部署的冷启动时间
  • 降低Java微服务的内存占用(RSS)
  • 为Maven或Gradle配置GraalVM原生构建工具
  • 解决原生构建中出现的
    ClassNotFoundException
    NoSuchMethodException
    或资源缺失错误
  • 生成或编辑
    reflect-config.json
    resource-config.json
    等GraalVM元数据文件
  • 使用GraalVM tracing agent收集可达性元数据
  • 为Spring Boot实现
    RuntimeHints
    原生支持
  • 为Quarkus或Micronaut构建原生镜像

Instructions

使用指南

1. Contextual Project Analysis

1. 项目上下文分析

Before any configuration, analyze the project to determine the build tool, framework, and dependencies:
Detect the build tool:
bash
undefined
在进行任何配置前,先分析项目确认构建工具、使用框架和依赖情况:
检测构建工具:
bash
undefined

Check for Maven

Check for Maven

if [ -f "pom.xml" ]; then echo "Build tool: Maven" # Check for Maven wrapper [ -f "mvnw" ] && echo "Maven wrapper available" fi
if [ -f "pom.xml" ]; then echo "Build tool: Maven" # Check for Maven wrapper [ -f "mvnw" ] && echo "Maven wrapper available" fi

Check for Gradle

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
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

**通过依赖分析检测使用框架:**

- **Spring Boot**: 在`pom.xml`或`build.gradle`中查找`spring-boot-starter-*`依赖
- **Quarkus**: 查找`quarkus-*`依赖
- **Micronaut**: 查找`micronaut-*`依赖
- **纯Java项目**: 未检测到框架依赖

**检查Java版本:**

```bash
java -version 2>&1

GraalVM Native Image requires Java 17+ (recommended: Java 21+)

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

**识别潜在的原生镜像构建挑战:**

- 重度依赖反射的库(Jackson、Hibernate、JAXB)
- 动态代理使用(JDK代理、CGLIB)
- 资源包和类路径资源
- JNI或原生库依赖
- 序列化需求

2. Build Tool Configuration

2. 构建工具配置

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:
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 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
根据检测到的环境配置对应的构建工具插件。
针对Maven项目,添加独立的
native
配置profile,避免影响标准构建流程。完整配置可参考Maven原生Profile参考
Maven核心配置:
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>
构建命令:
./mvnw -Pnative package
针对Gradle项目,应用
org.graalvm.buildtools.native
插件。完整配置可参考Gradle原生插件参考
Gradle核心配置(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")
        }
    }
}
构建命令:
./gradlew nativeCompile

3. Framework-Specific Configuration

3. 框架专属配置

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:
  • 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.
不同框架有各自的AOT策略,根据检测到的框架应用对应配置。
Spring Boot (3.x+):Spring Boot内置了GraalVM支持和AOT处理能力。相关方案包括
RuntimeHints
@RegisterReflectionForBinding
和测试支持,可参考Spring Boot原生开发参考
核心要点:
  • 使用3.x及以上版本的
    spring-boot-starter-parent
    ,已内置native profile
  • 通过
    RuntimeHintsRegistrar
    注册反射提示
  • 使用
    process-aot
    目标运行AOT处理
  • 构建命令:
    ./mvnw -Pnative native:compile
    ./gradlew nativeCompile
Quarkus和Micronaut:这两个框架是原生优先设计,仅需极少额外配置。可参考Quarkus & Micronaut原生开发参考

4. GraalVM Reachability Metadata

4. GraalVM可达性元数据

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>/
:
FilePurpose
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 for complete format and examples.
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访问注册配置
完整格式和示例可参考反射与资源配置参考

5. The Iterative Fix Engine

5. 迭代问题修复流程

Native image builds often fail due to missing metadata. Follow this iterative approach:
Step 1 — Execute the native build:
bash
undefined
原生镜像构建通常会因为元数据缺失失败,可遵循以下迭代流程解决:
步骤1 — 执行原生构建:
bash
undefined

Maven

Maven

./mvnw -Pnative package 2>&1 | tee native-build.log
./mvnw -Pnative package 2>&1 | tee native-build.log

Gradle

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).
./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自动收集可达性元数据,可参考[Tracing Agent使用参考](references/tracing-agent.md)。

6. Validation and Benchmarking

6. 验证与性能基准测试

Once the native build succeeds:
Verify the executable runs correctly:
bash
undefined
原生构建成功后:
验证可执行文件运行正常:
bash
undefined

Run the native executable

Run the native executable

./target/<app-name>
./target/<app-name>

For Spring Boot, verify the application context loads

For Spring Boot, verify the application context loads


**Measure startup time:**

```bash

**测量启动时间:**

```bash

Time the startup

Time the startup

time ./target/<app-name>
time ./target/<app-name>

For Spring Boot, check the startup log

For Spring Boot, check the startup log

./target/<app-name> 2>&1 | grep "Started .* in"

**Measure memory footprint (RSS):**

```bash
./target/<app-name> 2>&1 | grep "Started .* in"

**测量内存占用(RSS):**

```bash

On Linux

On Linux

ps -o rss,vsz,comm -p $(pgrep <app-name>)
ps -o rss,vsz,comm -p $(pgrep <app-name>)

On macOS

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 |
ps -o rss,vsz,comm -p $(pgrep <app-name>)

**与JVM基准版本对比:**

| 指标 | JVM | 原生版本 | 提升幅度 |
|--------|-----|--------|-------------|
| 启动时间 | ~2-5s | ~50-200ms | 10-100倍 |
| 内存(RSS) | ~200-500MB | ~30-80MB | 3-10倍 |
| 二进制体积 | JRE + JAR包 | 单二进制文件 | 部署更简化 |

7. Docker Integration

7. Docker集成

Build minimal container images with native executables:
dockerfile
undefined
使用原生可执行文件构建最小化容器镜像:
dockerfile
undefined

Multi-stage build

Multi-stage build

FROM ghcr.io/graalvm/native-image-community:21 AS builder WORKDIR /app COPY . . RUN ./mvnw -Pnative package -DskipTests
FROM ghcr.io/graalvm/native-image-community:21 AS builder WORKDIR /app COPY . . RUN ./mvnw -Pnative package -DskipTests

Minimal runtime image

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
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`:

```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
  1. 复杂项目优先使用tracing agent生成初始元数据基准
  2. 使用
    native
    profile
    将原生相关配置与标准构建隔离
  3. 优先使用
    --no-fallback
    参数
    确保生成纯原生构建(无JVM fallback)
  4. 使用
    nativeTest
    测试
    在原生模式下运行JUnit测试
  5. 使用GraalVM可达性元数据仓库获取第三方库的元数据
  6. 尽量减少反射使用——优先选择构造器注入和编译时依赖注入
  7. 显式配置资源引入规则,不要依赖类路径扫描
  8. 构建前后做性能 profiling——始终量化启动和内存优化效果
  9. 使用Java 21+版本获得最佳的GraalVM兼容性和性能
  10. 保持GraalVM和原生构建工具版本对齐

Examples

示例

Example 1: Adding Native Support to a Spring Boot Maven Project

示例1:为Spring Boot Maven项目添加原生支持

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
场景: 你有一个Spring Boot 3.x REST API项目,需要编译为原生可执行文件。
步骤1 — 在
pom.xml
中添加native profile:
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注册反射提示:
java
@RestController
@RegisterReflectionForBinding({UserDto.class, OrderDto.class})
public class UserController {

    @GetMapping("/users/{id}")
    public UserDto getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
}
步骤3 — 构建并运行:
bash
./mvnw -Pnative native:compile
./target/myapp

Started MyApplication in 0.089 seconds

Started MyApplication in 0.089 seconds

undefined
undefined

Example 2: Resolving a Reflection Error in Native Build

示例2:修复原生构建中的反射错误

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 { /* ... */ }
场景: 原生构建失败,提示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
json
{
  "reflection": [
    {
      "type": "com.example.dto.PaymentResponse",
      "allDeclaredConstructors": true,
      "allDeclaredMethods": true,
      "allDeclaredFields": true
    }
  ]
}
或使用Spring Boot注解方案:
java
@RegisterReflectionForBinding(PaymentResponse.class)
@Service
public class PaymentService { /* ... */ }

Example 3: Using the Tracing Agent for a Complex Project

示例3:为复杂项目使用Tracing Agent

Scenario: A project with many third-party libraries needs comprehensive reachability metadata.
bash
undefined
场景: 依赖大量第三方库的项目需要生成完整的可达性元数据。
bash
undefined

1. Build the JAR

1. Build the JAR

./mvnw package -DskipTests
./mvnw package -DskipTests

2. Run with the tracing agent

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
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image
-jar target/myapp.jar

3. Exercise all endpoints

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
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

4. Stop the application (Ctrl+C), then build native

./mvnw -Pnative native:compile
./mvnw -Pnative native:compile

5. Verify

5. Verify

./target/myapp
undefined
./target/myapp
undefined

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
  • GraalVM Native Image要求Java 17+(推荐Java 21+获得最佳兼容性)
  • 封闭世界假设:所有代码路径必须在构建时已知——动态类加载、运行时字节码生成、
    MethodHandles.Lookup
    可能无法正常工作
  • 构建时间与内存要求:原生编译资源消耗较高——普通项目预计需要2-10分钟、4-8GB内存
  • 并非所有库都兼容:重度依赖反射、动态代理或CGLIB的库可能需要大量元数据配置
  • AOT profile在构建时固定:Spring Boot的
    @Profile
    @ConditionalOnProperty
    在AOT处理阶段求值,而非运行时

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
  • 忘记添加
    --no-fallback
    参数
    :没有该参数时,构建可能静默生成JVM fallback镜像,而非纯原生可执行文件
  • Tracing Agent覆盖不完整:Agent仅会捕获运行时触发的代码路径——确保测试覆盖所有功能
  • 版本不匹配:保持GraalVM JDK、原生构建工具插件、框架版本对齐,避免兼容性问题
  • 类路径差异:AOT/构建阶段的类路径必须与运行时一致——原生编译后增删JAR包会导致运行失败

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
  • 原生可执行文件比JAR包更难反编译,但并非完全防篡改
  • 确保构建时不会将密钥等敏感信息嵌入原生镜像
  • 敏感数据使用环境变量或外部配置传入

Troubleshooting

故障排查

IssueSolution
Build runs out of memoryIncrease build memory:
-J-Xmx8g
in
buildArgs
Build takes too longUse build cache, reduce classpath, enable quick build mode for dev
Application crashes at runtimeMissing reflection/resource metadata — run tracing agent
Spring Boot context fails to loadCheck
@Conditional
beans and profile-dependent config
Third-party library not compatibleCheck GraalVM Reachability Metadata repo or add manual hints
问题解决方案
构建内存不足增加构建内存:在
buildArgs
中添加
-J-Xmx8g
构建耗时过长使用构建缓存、精简类路径、开发阶段启用快速构建模式
应用运行时崩溃反射/资源元数据缺失——运行tracing agent收集配置
Spring Boot上下文加载失败检查
@Conditional
Bean和依赖profile的配置
第三方库不兼容检查GraalVM可达性元数据仓库,或手动添加配置提示