You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot3+GraalVM Native Image构建含JDK预览特性应用失败解决方案

解决Spring Boot应用构建GraalVM Native Image时的预览特性报错问题

1. 调整pom.xml配置

要解决UnsupportedClassVersionError,需要在编译阶段和Native Image构建阶段都启用预览特性,具体配置如下:

(1)配置maven-compiler-plugin

确保Java代码编译时开启预览特性,替换<source>和<target>为你实际使用的JDK版本(需支持预览特性):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.11.0</version>
    <configuration>
        <source>21</source>
        <target>21</target>
        <compilerArgs>
            <arg>--enable-preview</arg>
        </compilerArgs>
    </configuration>
</plugin>

(2)配置spring-boot-maven-plugin

如果用Buildpacks构建镜像(即你当前使用的spring-boot:build-image命令),需要在镜像构建参数中加入--enable-preview:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <image>
            <env>
                <BP_NATIVE_IMAGE_BUILD_ARGUMENTS>--enable-preview</BP_NATIVE_IMAGE_BUILD_ARGUMENTS>
            </env>
        </image>
    </configuration>
</plugin>

如果是直接用GraalVM的native-maven-plugin构建Native Image文件,配置如下:

<plugin>
    <groupId>org.graalvm.buildtools</groupId>
    <artifactId>native-maven-plugin</artifactId>
    <configuration>
        <buildArgs>
            <arg>--enable-preview</arg>
        </buildArgs>
    </configuration>
</plugin>

2. 执行构建命令

配置完成后,直接运行你原来的命令即可:

mvn -Pnative spring-boot:build-image

如果不想修改pom,也可以通过命令行临时传递参数(仅适用于Buildpacks方式):

mvn -Pnative spring-boot:build-image -Dspring-boot.build-image.env.BP_NATIVE_IMAGE_BUILD_ARGUMENTS=--enable-preview

关键注意事项

  • 你的GraalVM版本必须与JDK版本匹配,且该GraalVM版本支持对应JDK的预览特性;
  • 预览特性不属于JDK稳定特性,不同版本的JDK/GraalVM对预览特性的支持可能有差异,需确保代码使用的特性在目标环境中可用。

内容的提问来源于stack exchange,提问作者PatPanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 13:38:19