How can I use a specific maven version that uses a lower java version for building my project?

358 Views Asked by At

In my maven project is dependent on java 8 and I want maven to assume the same while building the project. But currently my installed maven is using java 21. How do I make it use java 8 for building the project. I have already included the required java version in pom.xml in properties and maven-compiler-plugin configuration. The output of this command shows its using java 21 : mvn -version

Maven home: /usr/local/Cellar/maven/3.9.6/libexec
Java version: 21.0.1, vendor: Homebrew, runtime: /usr/local/Cellar/openjdk/21.0.1/libexec/openjdk.jdk/Contents/Home
Default locale: en_IN, platform encoding: UTF-8
OS name: "mac os x", version: "13.4.1", arch: "x86_64", family: "mac"

And this is the error I get on running mvn clean install :

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project mtl-billing: Fatal error compiling: java.lang.NoSuchFieldError: Class com.sun.tools.javac.tree.JCTree$JCImport does not have member field 'com.sun.tools.javac.tree.JCTree qualid' -> [Help 1]

I think this is related to the java version. And if I make maven use java 8 somehow , it should work. I have java 8. Output of command "which java" gives:
/usr/local/opt/openjdk@8/bin/java

I tried including a lower maven version in pom.xml under properties

<properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.version>3.0.4</maven.version>
    </properties>

But that actually doesn't make it run with a lower version.

1

There are 1 best solutions below

0
wi2ard On

From the maven install docs, to use maven you need:

Either set the JAVA_HOME environment variable pointing to your JDK installation or have the java executable on your PATH

That is how maven decides which JDK installation to use so you need to check the values of these environment variables. See if homebrew has an option to change these values, JENV does if you use it. You can also set these variables manually. This assumes that you want to use the same JDK everywhere in your system, ie. you build with JDK 8 and then deploy on servers run on JDK 8 also, etc.

If you need more flexibility and you want to decouple your project build from the version of JDK installed then use Maven toolchains