如何在Spring Boot Gradle项目中成功切换至Java 11?
问题
使用IntelliJ创建Spring Boot Gradle项目时选择了Java 17,build.gradle中配置sourceCompatibility = '17'。但系统JAVA_HOME为Java 11,不想切换系统Java版本或重建项目。尝试将sourceCompatibility改为'11',并在IntelliJ的File -> Project Structure -> Project Settings -> Project中切换SDK为11后,无论通过IDE运行还是执行./gradlew clean build,均出现兼容报错,部分错误信息如下:
> Could not resolve org.springframework.boot:spring-boot-gradle-plugin:3.0.1-SNAPSHOT. Required by: project : > org.springframework.boot:org.springframework.boot.gradle.plugin:3.0.1-SNAPSHOT:20221222.181044-39 > No matching variant of org.springframework.boot:spring-boot-gradle-plugin:3.0.1-SNAPSHOT:20221222.181044-39 was found. The consumer was configured to find a runtime of a library compatible with Java 11, packaged as a jar, and its dependencies declared externally, as well as attribute 'org.gradle.plugin.api-version' with value '7.6' but: - Variant 'apiElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.1-SNAPSHOT declares a library, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares an API of a component compatible with Java 17 and the consumer needed a runtime of a component compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '7.6') - Variant 'javadocElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.1-SNAPSHOT declares a runtime of a component, and its dependencies declared externally:
解决方法
1. 降级Spring Boot版本到Java 11兼容分支
Spring Boot 3.x及以上最低要求Java 17,需切换到2.x系列(推荐2.7.x稳定分支)。
修改项目根目录的构建文件:
Groovy DSL (build.gradle)
plugins { id 'org.springframework.boot' version '2.7.14' id 'io.spring.dependency-management' version '1.0.15.RELEASE' id 'java' } sourceCompatibility = '11' targetCompatibility = '11'
Kotlin DSL (build.gradle.kts)
plugins { id("org.springframework.boot") version "2.7.14" id("io.spring.dependency-management") version "1.0.15.RELEASE" java } java { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 }
2. 配置Gradle使用Java 11(不依赖系统JAVA_HOME)
方式一:通过gradle.properties指定JDK路径
在项目根目录的gradle.properties中添加:
org.gradle.java.home=/path/to/your/java11/jdk
替换路径为本地Java 11的实际安装目录(如Mac下/Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home,Windows下C:\Program Files\Java\jdk-11.0.20)。
方式二:IntelliJ中指定Gradle JVM
打开File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle,在Gradle JVM下拉菜单选择本地已安装的Java 11 SDK,点击Apply保存后同步项目(点击右上角Sync Project with Gradle Files)。
3. 确认模块级SDK配置
打开File -> Project Structure -> Project Settings -> Modules:
- 切换到
Sources标签,设置Language level为11 - Local variable syntax for lambda parameters; - 切换到
Dependencies标签,设置Module SDK为Java 11。
4. 清理并重新构建项目
执行命令行:
./gradlew clean build
或在IntelliJ中选择Build -> Rebuild Project。
内容的提问来源于stack exchange,提问作者aCarella

