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

使用Maven Toolchain时exec插件无法启用Java预览特性

解决exec-maven-plugin未使用Maven Toolchain指定JDK的问题

问题根源

exec-maven-plugin默认会使用启动Maven的系统默认JVM(即你的Java 17)来执行代码,不会自动继承toolchain插件配置的JDK环境,导致编译好的Java 19字节码用Java 17运行时抛出java.lang.UnsupportedClassVersionError。

解决方案1:配置exec插件使用toolchain的JDK可执行文件

在exec-maven-plugin的配置中,通过${java.home}(由toolchain插件注入的属性)指定Java 19的java可执行文件路径,同时保留--enable-preview参数:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <!-- 引用toolchain配置的JDK的java命令 -->
        <executable>${java.home}/bin/java</executable>
        <arguments>
            <argument>--enable-preview</argument>
            <argument>-cp</argument>
            <argument>${project.build.outputDirectory}</argument>
            <!-- 替换为你的主类全限定名 -->
            <argument>com.example.Main</argument>
        </arguments>
    </configuration>
</plugin>

解决方案2:确保toolchain插件提前执行

将maven-toolchains-plugin绑定到更早的生命周期阶段(默认validate阶段),确保在exec插件运行前完成JDK环境的注入:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-toolchains-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <goals>
                <goal>toolchain</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <toolchains>
            <jdk>
                <version>19</version>
                <vendor>openjdk</vendor>
            </jdk>
        </toolchains>
    </configuration>
</plugin>

验证toolchain配置正确性

确认~/.m2/toolchains.xml中Java 19的配置路径和版本匹配:

<?xml version="1.0" encoding="UTF-8"?>
<toolchains>
    <toolchain>
        <type>jdk</type>
        <provides>
            <version>19</version>
            <vendor>openjdk</vendor>
        </provides>
        <configuration>
            <jdkHome>/实际的JDK19安装路径</jdkHome>
        </configuration>
    </toolchain>
</toolchains>

完成配置后,重新执行mvn clean package exec:java即可正常运行Java 19预览特性的代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:40:29