Java Version Mismatch for Gradle Build

Java Version Mismatch for Gradle Build

How to Fix Gradle Error: Dependency requires at least JVM runtime version 17. This build uses a Java 8 JVM

In this tutorial, we are going to learn how to resolve the Java version mismatch issue for a Gradle build in a Spring Framework, Spring Boot project.

Problem

When building a Spring Boot application with Gradle, we might encounter the following issue.
bash
Dependency requires at least JVM runtime version 17. This build uses a Java 8 JVM
This is the Java version mismatch when running the following command in a Spring Boot application.
bash
 ./gradlew build

Why does this happen?

This is due to a disconnect or mismatch between the executable Java version and the JAVA_HOME environment variable.
While running java -version it might show that Java 17 is installed, the Gradle Wrapper (gradlew) specifically depends on the JAVA_HOME environment variable to locate the JDK. If JAVA_HOME is still pointing to an older Java 8 installation, the issue occurs with the build failing.

How to Fix It

Verify the Java version

First, let's verify the installed Java version
bash
java --version
You can verify the active Java version installed as:
bash
readlink -f $(which java)
Output:
bash
/usr/lib/jvm/java-17-openjdk-amd64/bin/java
Note that the directory path will be /usr/lib/jvm/java-17-openjdk-amd64 (excluding the /bin/java ).
Make sure the Java version used to create a project matches the installed version.
If you haven't found the specific version, download the JDK-specific version from the Java archive

Update the bashrc file

Lets setup the JAVA_HOME path. Here, we are using Ubuntu, so let's do it on it.
Open the bashrc file
bash
sudo vi ~/.bashrc
Add the following setup
bash
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
export PATH=$PATH:$JAVA_HOME/bin
Make sure to use the exact path of JDK; in our case, it is inside /usr/lib/jvm/java-17-openjdk-amd64
If you are using the old JAVA_HOME setup, update it with the new version of Java so the mismatch issue will be resolved.

Apply the changes

Save the file, press Esc
bash
:wq!

Reload the changes

Now reload the changes
bash
source ~/.bashrc

Verify the changes

bash
echo $JAVA_HOME
Now the setup is completed. You can check by running the Gradle Spring Boot project.
bash
./gradlew clean build
Your Gradle wrapper will now use the setup JDK 17, resulting in a version mismatch issue.