Java 21编译报错:使用--enable-preview时源版本18无效求助
解决Spring Boot编译错误:invalid source release 18 with --enable-preview
错误原因
启用了Java预览语言特性,但当前编译环境使用的JDK版本是18,而POM中指定的Java版本为21,Java预览特性仅支持与指定JDK版本完全匹配的编译环境。
解决步骤
1. 修正Maven编译器插件配置
在POM的<build><plugins>节点中添加maven-compiler-plugin配置,明确指定Java版本并启用预览特性,覆盖默认设置:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.12.1</version> <configuration> <source>21</source> <target>21</target> <release>21</release> <compilerArgs> --enable-preview </compilerArgs> </configuration> </plugin>
2. 检查IDE项目配置
IntelliJ IDEA:
- 打开
File > Project Structure,在Project选项中设置Project SDK为JDK 21,Project language level选择21 (Preview) - Virtual threads, Record patterns, etc. - 进入
Modules选项,确保所有模块的Language level同步设置为21预览版 - 打开
Settings > Build, Execution, Deployment > Compiler > Java Compiler,对应模块的Target bytecode version设为21,勾选Enable preview features
- 打开
Eclipse:
- 右键项目选择
Properties > Java Build Path,在Libraries中替换为JDK 21 - 进入
Properties > Java Compiler,勾选Enable preview features for Java 21,设置Compiler compliance level为21
- 右键项目选择
3. 验证全局JDK配置
确保系统环境变量JAVA_HOME指向JDK 21,同时IDE的SDKs配置中已正确添加JDK 21。
内容的提问来源于stack exchange,提问作者mitiku
相关产品推荐
相关产品推荐

