Maven uses the JAVA_HOME
parameter to find which Java version it is supposed to run. I see from your comment that you can’t change that in the configuration.
- You can set the
JAVA_HOME
parameter just before you start maven (and change it back afterwards if need be). - You could also go into your
mvn
(non-windows)/mvn.bat
/mvn.cmd
(windows) and set your java version explicitly there.
answered Oct 29, 2013 at 9:47
DanielBarbarianDanielBarbarian
4,94312 gold badges34 silver badges43 bronze badges
4
Edit:
A better solution is presented by the answer from Ondrej, which obviates remembering aliases.
Original Answer:
Adding a solution for people with multiple Java versions installed
We have a large codebase, most of which is in Java. The majority of what I work on is written in either Java 1.7 or 1.8. Since JAVA_HOME
is static, I created aliases in my .bashrc
for running Maven with different values:
alias mvn5="JAVA_HOME=/usr/local/java5 && mvn"
alias mvn6="JAVA_HOME=/usr/local/java6 && mvn"
alias mvn7="JAVA_HOME=/usr/local/java7 && mvn"
alias mvn8="JAVA_HOME=/usr/local/java8 && mvn"
This lets me run Maven from the command line on my development machine regardless of the JDK version used on the project.
answered Apr 20, 2017 at 16:09
7
In the POM, you can set the compiler properties, e.g. for 1.8:
<project>
...
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
...
</project>
answered Mar 30, 2017 at 15:38
Edward RossEdward Ross
2,5541 gold badge17 silver badges17 bronze badges
4
I just recently, after seven long years with Maven, learned about toolchains.xml. Maven has it even documented and supports it from 2.0.9 — toolchains documentation
So I added a toolchains.xml file to my ~/.m2/ folder with following content:
<toolchains xmlns="http://maven.apache.org/TOOLCHAINS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/TOOLCHAINS/1.1.0 http://maven.apache.org/xsd/toolchains-1.1.0.xsd">
<!-- JDK toolchains -->
<toolchain>
<type>jdk</type>
<provides>
<version>1.8</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/opt/java8</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>1.7</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/opt/java7</jdkHome>
</configuration>
</toolchain>
</toolchains>
It allows you to define what different JDKs Maven can use to build the project irrespective of the JDK Maven runs with. Sort of like when you define JDK on project level in IDE.
simon
12.5k25 gold badges77 silver badges110 bronze badges
answered Feb 17, 2016 at 17:27
Ondrej BurkertOndrej Burkert
6,3472 gold badges32 silver badges26 bronze badges
7
On windows
If you do not want to change your JAVA_HOME
variable inside the system variables.
Edit your mvn.bat
file and add a line like this
set JAVA_HOME=C:Program FilesJavajdk1.7.0_45jre
This can be done after @REM ==== START VALIDATION ====
like mentionned by @Jonathan
On Mac (& Linux ?)
If you do not want to change your JAVA_HOME
variable inside your ~/.bashrc
or ~/.bash_profile
you can create a ~/.mavenrc
file and redefine your JAVA_HOME
using the java_home tool
export JAVA_HOME=`/usr/libexec/java_home -v 1.7.0_45`
Sanity Check
You can verify that everything is working fine by executing the following commands. The jdk version should be different.
mvn -version
then
java -version
answered Jul 30, 2015 at 8:11
Ronan QuillevereRonan Quillevere
3,5491 gold badge28 silver badges42 bronze badges
4
Adding my two cents and explicitly providing the solution.
I have two JDKs installed on my Windows Machine — JDK 1.5
and JDK 1.6
.
My default (and set to windows system environment variable) JAVA_HOME
is set to JDK 1.5
.
However, I have a maven project that I need to build (i.e., JBehave Tutorial’s Etsy.com) using JDK 1.6
.
My solution in this scenario (which worked!), is as suggested by @DanielBarbarian
to set it in mvn.bat
.
For some not familiar with window’s batch file, I just basically added the set JAVA_HOME=<path_to_other_jdk>
line after @REM ==== START VALIDATION ====
in mvn.bat
(i.e., %MAVEN_HOME%binmvn.bat
):
@REM ==== START VALIDATION ====
set JAVA_HOME=C:Program FilesJavajdk1.6.0_45jre
if not "%JAVA_HOME%" == "" goto OkJHome
answered May 8, 2014 at 2:49
JonathanJonathan
2,1941 gold badge22 silver badges29 bronze badges
1
You can set Maven to use any java version following the instructions below.
Install jenv in your machine link
Check the available java versions installed in your machine by issuing the following command in command line.
jenv versions
You can specify global Java version using the following command.
jenv global oracle64-1.6.0.39
You can specify local Java version for any directory(Project) using the following command in the directory in command line.
jenv local oracle64-1.7.0.11
add the correct java version in your pom.xml
if you are running maven in command line install jenv maven plugin using below command
jenv enable-plugin maven
Now you can configure any java version in your machine to any project with out any trouble.
answered Jun 7, 2019 at 2:45
RanukaRanuka
7637 silver badges13 bronze badges
1
One simple solution to the problem —
JAVA_HOME=/usr/lib/jvm/java-6-sun/ mvn clean install
On Mac, it would look something like —
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home/ mvn clean install
PS: One special case that i found is the above given command does not work on ‘fish’ shell. I also had bash shell available and it worked fine there. just use command ‘bash’ to switch to bash shell.
answered Mar 3, 2017 at 12:23
PankajPankaj
3523 silver badges12 bronze badges
On Macs, (assuming you have the right version installed)
JAVA_HOME=`/usr/libexec/java_home -v 1.8` mvn clean install -DskipTests
answered Aug 20, 2019 at 16:17
You could configure compiling sources using different JDK with maven-compiler-plugin
.
Just specify path to javac
in <executable>
tag. E.g for java11 it looks like:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
<fork>true</fork>
<executable>C:Program FilesJavajdk-11.0.1binjavac</executable> <!--PATH TO JAVAC -->
</configuration>
</plugin>
answered Mar 30, 2019 at 21:57
RuslanRuslan
5,9901 gold badge20 silver badges36 bronze badges
I am using Mac and none of the answers above helped me. I found out that maven loads its own JAVA_HOME from the path specified in: ~/.mavenrc
I changed the content of the file to be:
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
For Linux it will look something like:
export JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre
answered Oct 6, 2021 at 10:40
TechnotronicTechnotronic
8,1643 gold badges40 silver badges53 bronze badges
On windows, I just add multiple batch files for different JDK versions to the Maven bin folder like this:
mvn11.cmd
@echo off
setlocal
set "JAVA_HOME=pathtojdk11"
set "path=%JAVA_HOME%;%path%"
mvn %*
then you can use mvn11
to run Maven in the specified JDK.
answered Jul 4, 2019 at 6:56
Talis GuoTalis Guo
1161 silver badge4 bronze badges
2
Without changing Environment Variables, You can manage java version based on the project level by using Maven Compiler Plugin.
Method 1
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Method 2
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
answered Oct 22, 2019 at 8:48
To avoid any impact to your project and to your Environment Variables, you can configure the Maven Compiler Plugin just to the project’s POM, specifying the Source and Target java version
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
...
</plugins>
answered Feb 2, 2017 at 9:25
ToninoTonino
1,10710 silver badges24 bronze badges
I did not have success on mac with just setting JAVA_HOME
in the console but I was successful with this approach
- Create .mavenrc file at your at your home directory (so the file will path will be
~/.mavenrc
- Into that file paste
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
answered Jan 31, 2019 at 14:20
Martin VichMartin Vich
1,0521 gold badge7 silver badges22 bronze badges
- on terminal
vi ~/.bash_profile
- After that, paste the below path in the base profile file and save it by vim command
wq!
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home
export M2_HOME=/Users/mj/Tools/apache-maven-3.8.1
-
run
source ~/.bash_profile
to make it work forever -
after that, you can run
mvn -v
in your terminal to check
Maven home: /Users/mj/Tools/apache-maven-3.8.1
Java version: 1.8.0_211, vendor: Oracle Corporation,
runtime: /Users/mj/Tools/jdk1.8.0_211.jdk/Contents/Home/jre
Default locale: en_CN, platform encoding: UTF-8
OS name: "mac os x", version: "10.16", arch: "x86_64", family: "mac"
if you want to know why, read below
JAVA_HOME is used by many Java-based applications to define the place of Java Runtime Environment (JRE) installation.
M2_HOME is used by Maven, and again it tells the program where to find Maven installation.
answered May 27, 2021 at 3:21
2
Recently installed Java10 to see whats new and fun about it. Once I did this and tried running existing projects which use java8.
To my surprise, maven began using java10 as its default java version, even though my JAVA_HOME is set to use java8 — /usr/libexec/java_home -v 1.8
Given, my installation was done using brew — Brew is simply a package manager for Mac OS, my M2_HOME was automatically set up. This is usually in /usr/local/Cellar/maven/3.5.4
With this new found knowledge, I run
nano /usr/local/Cellar/maven/3.5.4/bin/mvn
The content was
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-$(/usr/libexec/java_home)}" exec "/usr/local/Cellar/maven/3.5.4/libexec/bin/mvn" "$@"
Important bit being
"${JAVA_HOME:-$(/usr/libexec/java_home)}"
To resolve this, you will need to specify the java version you need maven to default to. So in my case, I needed java8.
Update /usr/local/Cellar/maven/3.5.4/bin/mvn
file as follows
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-$(/usr/libexec/java_home -v 1.8)}" exec "/usr/local/Cellar/maven/3.5.4/libexec/bin/mvn" "$@"
Paulo Merson
12.6k7 gold badges77 silver badges72 bronze badges
answered Mar 9, 2021 at 3:25
1
You just need to add your JAVA version to mvn file before the call of JAVA_HOME
for example my JAVA Version in .bashrc file is Java-17
and i want to run maven with Java-11 :
in file /usr/share/maven/bin/mvn
:
I add :
JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
before the call of JAVA_HOME
in the script
and then it works fine with Java-11
answered Jan 8, 2022 at 20:13
set JAVA_HOME=C:Program FilesJavajdk1.7.0_45jre
Adding the above line of code as the first statement in $MAVEN_HOMEbinmvn.cmd
worked for me straight away in Windows 10.
answered Jan 17, 2022 at 17:13
I couldn’t solve this problem with the answers above and I tried many things to solve this and I got it. I hope someone like me could solve the problem.
I am using brew to install java and maven.
For me, I wanted to use java 1.8. So I installed java 1.8
but still maven use version 17.0.2
Solution:
install java 1.8
I referred to this website to install it: https://devqa.io/brew-install-java/
mvn --version
and remember the version
cat /usr/local/Cellar/maven/VERSION(for me 3.8.5)/bin/mvn
Then you will see
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-/usr/local/opt/openjdk/libexec/openjdk.jdk/Contents/Home}" exec "/usr/local/Cellar/maven/3.8.5/libexec/bin/mvn" "$@"
Check this directory
ls /usr/local/opt
You will see files like openjdk, openjdk@17, openjdk@8
change the directory openjdk to openjdk@8 in mvn file:
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-/usr/local/opt/openjdk@8/libexec/openjdk.jdk/Contents/Home}" exec "/usr/local/Cellar/maven/3.8.5/libexec/bin/mvn" "$@"
answered Mar 30, 2022 at 3:04
Ondrej’s answer
worked perfectly. It truly solves the problem. Few other things to do though as detailed in the toolchain documentation
- Add the maven-toolchains-plugin in your project POM
- Configure the maven-toolchains-plugin to use a specific JDK in the toolchain as configured in your toolchains.xml file.
See sample configurations below:
toolchains.xml
<toolchains xmlns="http://maven.apache.org/TOOLCHAINS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/TOOLCHAINS/1.1.0 http://maven.apache.org/xsd/toolchains-1.1.0.xsd">
<!-- JDK toolchains -->
<toolchain>
<type>jdk</type>
<provides>
<version>1.8</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/Library/Java/JavaVirtualMachines/jdk1.8.0_301.jdk/Contents/Home</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>17</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>11</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/Library/Java/JavaVirtualMachines/jdk-11.0.12.jdk/Contents/Home</jdkHome>
</configuration>
</toolchain>
</toolchains>
As seen above, this works for machines having multiple java versions installed.
Then in the project’s POM, the maven-toolchains-plugin is configured to use one of the JDK versions defined as a toolchain.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-toolchains-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>toolchain</goal>
</goals>
</execution>
</executions>
<configuration>
<toolchains>
<jdk>
<version>11</version>
<vendor>sun</vendor>
</jdk>
</toolchains>
</configuration>
</plugin>
answered Apr 7, 2022 at 7:43
mikaelovimikaelovi
1014 silver badges10 bronze badges
Also you can have two versions of maven installed, and edit one of them, editing here:
mvn(non-windows)/mvn.bat/mvn.cmd(windows)
replacing your %java_home% appearances to your java desired path. Then just execute maven from that modified path
answered Dec 13, 2018 at 10:33
I’ve used the base idea from @Jonathan.
I’ve set the windows with: set JAVA_HOME=C:Program FilesjavaAdoptOpenJDK-11.0.8+10
call mvn clean package -DskipTests
answered Oct 9, 2020 at 0:01
GtdDevGtdDev
6805 silver badges12 bronze badges
I am using jenv and was facing the compilation error for «javax.xml.bind.annotation» as the mvn in terminal was using openjdk 13
Maven home: /usr/local/Cellar/maven/3.6.3_1/libexec
Java version: 13.0.2, vendor: N/A, runtime: /usr/local/Cellar/openjdk/13.0.2+8_2/libexec/openjdk.jdk/Contents/Home
For me, it worked after running ‘jenv enable-plugin maven’ as suggested here
https://stackoverflow.com/a/56487374/1582473
answered Apr 12, 2021 at 17:52
Mac Users,
If you have installed maven from HomeBrew(Brew),
Or even if you have installed it from elsewhere,
If you want to change the default version of the Java used by the Maven,
You can use following commands to change the version that the maven uses,
vim ~/.mavenrc
In the gui that pops up enter this and save-
JAVA_HOME="(put the Home path of your desired java version package)"
To verify wether the path is changed for maven you can check using —
mvn -v
answered Aug 24, 2022 at 7:14
Setting the Default Java Version
You might have 2 different versions of Java on your system. To set one as the default , use the command:
sudo alternatives ––config java
The system displays a list of different Java versions. If you like the default, press Enter.
If you want to change it, type the number of the version you want, then press Enter.
answered Sep 29, 2022 at 11:11
I am using MAC Mini — M1 chip, after installing maven through brew install maven I noticed it’s using java 19 but I rather wanted to use java 17 version that I downloaded in to my machine. Was out of luck with specific instructions to reset the default mvn java version. Here are the steps you can follow.
mvn --version
#this will give where the maven is installed
in my case Maven home:/opt/homebrew/Cellar/maven/3.8.7/libexec
- then go to
/opt/homebrew/Cellar/maven/3.8.7/bin
folder - edit mvn file, I used
vi mvn
- below I have edited the jdk location to point where I have java 17 jdk
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-/Library/Java/JavaVirtualMachines/jdk-17.0.3.1.jdk/Contents/Home}" exec "/opt/homebrew/Cellar/maven/3.8.7/libexec/bin/mvn" "$@"
- save the mvn file after edit
mvn -v
will now show it’s default java version is 17
Apache Maven 3.8.7 (b89d5959fcde851dcb1c8946a785a163f14e1e29)
Maven home: /opt/homebrew/Cellar/maven/3.8.7/libexec
Java version: 17.0.3.1, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk-17.0.3.1.jdk/Contents/Home
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "13.1", arch: "aarch64", family: "mac"
hamid
2,0074 gold badges21 silver badges42 bronze badges
answered Jan 28 at 23:26
Maven uses the JAVA_HOME
parameter to find which Java version it is supposed to run. I see from your comment that you can’t change that in the configuration.
- You can set the
JAVA_HOME
parameter just before you start maven (and change it back afterwards if need be). - You could also go into your
mvn
(non-windows)/mvn.bat
/mvn.cmd
(windows) and set your java version explicitly there.
answered Oct 29, 2013 at 9:47
DanielBarbarianDanielBarbarian
4,94312 gold badges34 silver badges43 bronze badges
4
Edit:
A better solution is presented by the answer from Ondrej, which obviates remembering aliases.
Original Answer:
Adding a solution for people with multiple Java versions installed
We have a large codebase, most of which is in Java. The majority of what I work on is written in either Java 1.7 or 1.8. Since JAVA_HOME
is static, I created aliases in my .bashrc
for running Maven with different values:
alias mvn5="JAVA_HOME=/usr/local/java5 && mvn"
alias mvn6="JAVA_HOME=/usr/local/java6 && mvn"
alias mvn7="JAVA_HOME=/usr/local/java7 && mvn"
alias mvn8="JAVA_HOME=/usr/local/java8 && mvn"
This lets me run Maven from the command line on my development machine regardless of the JDK version used on the project.
answered Apr 20, 2017 at 16:09
7
In the POM, you can set the compiler properties, e.g. for 1.8:
<project>
...
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
...
</project>
answered Mar 30, 2017 at 15:38
Edward RossEdward Ross
2,5541 gold badge17 silver badges17 bronze badges
4
I just recently, after seven long years with Maven, learned about toolchains.xml. Maven has it even documented and supports it from 2.0.9 — toolchains documentation
So I added a toolchains.xml file to my ~/.m2/ folder with following content:
<toolchains xmlns="http://maven.apache.org/TOOLCHAINS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/TOOLCHAINS/1.1.0 http://maven.apache.org/xsd/toolchains-1.1.0.xsd">
<!-- JDK toolchains -->
<toolchain>
<type>jdk</type>
<provides>
<version>1.8</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/opt/java8</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>1.7</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/opt/java7</jdkHome>
</configuration>
</toolchain>
</toolchains>
It allows you to define what different JDKs Maven can use to build the project irrespective of the JDK Maven runs with. Sort of like when you define JDK on project level in IDE.
simon
12.5k25 gold badges77 silver badges110 bronze badges
answered Feb 17, 2016 at 17:27
Ondrej BurkertOndrej Burkert
6,3472 gold badges32 silver badges26 bronze badges
7
On windows
If you do not want to change your JAVA_HOME
variable inside the system variables.
Edit your mvn.bat
file and add a line like this
set JAVA_HOME=C:Program FilesJavajdk1.7.0_45jre
This can be done after @REM ==== START VALIDATION ====
like mentionned by @Jonathan
On Mac (& Linux ?)
If you do not want to change your JAVA_HOME
variable inside your ~/.bashrc
or ~/.bash_profile
you can create a ~/.mavenrc
file and redefine your JAVA_HOME
using the java_home tool
export JAVA_HOME=`/usr/libexec/java_home -v 1.7.0_45`
Sanity Check
You can verify that everything is working fine by executing the following commands. The jdk version should be different.
mvn -version
then
java -version
answered Jul 30, 2015 at 8:11
Ronan QuillevereRonan Quillevere
3,5491 gold badge28 silver badges42 bronze badges
4
Adding my two cents and explicitly providing the solution.
I have two JDKs installed on my Windows Machine — JDK 1.5
and JDK 1.6
.
My default (and set to windows system environment variable) JAVA_HOME
is set to JDK 1.5
.
However, I have a maven project that I need to build (i.e., JBehave Tutorial’s Etsy.com) using JDK 1.6
.
My solution in this scenario (which worked!), is as suggested by @DanielBarbarian
to set it in mvn.bat
.
For some not familiar with window’s batch file, I just basically added the set JAVA_HOME=<path_to_other_jdk>
line after @REM ==== START VALIDATION ====
in mvn.bat
(i.e., %MAVEN_HOME%binmvn.bat
):
@REM ==== START VALIDATION ====
set JAVA_HOME=C:Program FilesJavajdk1.6.0_45jre
if not "%JAVA_HOME%" == "" goto OkJHome
answered May 8, 2014 at 2:49
JonathanJonathan
2,1941 gold badge22 silver badges29 bronze badges
1
You can set Maven to use any java version following the instructions below.
Install jenv in your machine link
Check the available java versions installed in your machine by issuing the following command in command line.
jenv versions
You can specify global Java version using the following command.
jenv global oracle64-1.6.0.39
You can specify local Java version for any directory(Project) using the following command in the directory in command line.
jenv local oracle64-1.7.0.11
add the correct java version in your pom.xml
if you are running maven in command line install jenv maven plugin using below command
jenv enable-plugin maven
Now you can configure any java version in your machine to any project with out any trouble.
answered Jun 7, 2019 at 2:45
RanukaRanuka
7637 silver badges13 bronze badges
1
One simple solution to the problem —
JAVA_HOME=/usr/lib/jvm/java-6-sun/ mvn clean install
On Mac, it would look something like —
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home/ mvn clean install
PS: One special case that i found is the above given command does not work on ‘fish’ shell. I also had bash shell available and it worked fine there. just use command ‘bash’ to switch to bash shell.
answered Mar 3, 2017 at 12:23
PankajPankaj
3523 silver badges12 bronze badges
On Macs, (assuming you have the right version installed)
JAVA_HOME=`/usr/libexec/java_home -v 1.8` mvn clean install -DskipTests
answered Aug 20, 2019 at 16:17
You could configure compiling sources using different JDK with maven-compiler-plugin
.
Just specify path to javac
in <executable>
tag. E.g for java11 it looks like:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
<fork>true</fork>
<executable>C:Program FilesJavajdk-11.0.1binjavac</executable> <!--PATH TO JAVAC -->
</configuration>
</plugin>
answered Mar 30, 2019 at 21:57
RuslanRuslan
5,9901 gold badge20 silver badges36 bronze badges
I am using Mac and none of the answers above helped me. I found out that maven loads its own JAVA_HOME from the path specified in: ~/.mavenrc
I changed the content of the file to be:
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
For Linux it will look something like:
export JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre
answered Oct 6, 2021 at 10:40
TechnotronicTechnotronic
8,1643 gold badges40 silver badges53 bronze badges
On windows, I just add multiple batch files for different JDK versions to the Maven bin folder like this:
mvn11.cmd
@echo off
setlocal
set "JAVA_HOME=pathtojdk11"
set "path=%JAVA_HOME%;%path%"
mvn %*
then you can use mvn11
to run Maven in the specified JDK.
answered Jul 4, 2019 at 6:56
Talis GuoTalis Guo
1161 silver badge4 bronze badges
2
Without changing Environment Variables, You can manage java version based on the project level by using Maven Compiler Plugin.
Method 1
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Method 2
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
answered Oct 22, 2019 at 8:48
To avoid any impact to your project and to your Environment Variables, you can configure the Maven Compiler Plugin just to the project’s POM, specifying the Source and Target java version
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
...
</plugins>
answered Feb 2, 2017 at 9:25
ToninoTonino
1,10710 silver badges24 bronze badges
I did not have success on mac with just setting JAVA_HOME
in the console but I was successful with this approach
- Create .mavenrc file at your at your home directory (so the file will path will be
~/.mavenrc
- Into that file paste
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
answered Jan 31, 2019 at 14:20
Martin VichMartin Vich
1,0521 gold badge7 silver badges22 bronze badges
- on terminal
vi ~/.bash_profile
- After that, paste the below path in the base profile file and save it by vim command
wq!
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home
export M2_HOME=/Users/mj/Tools/apache-maven-3.8.1
-
run
source ~/.bash_profile
to make it work forever -
after that, you can run
mvn -v
in your terminal to check
Maven home: /Users/mj/Tools/apache-maven-3.8.1
Java version: 1.8.0_211, vendor: Oracle Corporation,
runtime: /Users/mj/Tools/jdk1.8.0_211.jdk/Contents/Home/jre
Default locale: en_CN, platform encoding: UTF-8
OS name: "mac os x", version: "10.16", arch: "x86_64", family: "mac"
if you want to know why, read below
JAVA_HOME is used by many Java-based applications to define the place of Java Runtime Environment (JRE) installation.
M2_HOME is used by Maven, and again it tells the program where to find Maven installation.
answered May 27, 2021 at 3:21
2
Recently installed Java10 to see whats new and fun about it. Once I did this and tried running existing projects which use java8.
To my surprise, maven began using java10 as its default java version, even though my JAVA_HOME is set to use java8 — /usr/libexec/java_home -v 1.8
Given, my installation was done using brew — Brew is simply a package manager for Mac OS, my M2_HOME was automatically set up. This is usually in /usr/local/Cellar/maven/3.5.4
With this new found knowledge, I run
nano /usr/local/Cellar/maven/3.5.4/bin/mvn
The content was
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-$(/usr/libexec/java_home)}" exec "/usr/local/Cellar/maven/3.5.4/libexec/bin/mvn" "$@"
Important bit being
"${JAVA_HOME:-$(/usr/libexec/java_home)}"
To resolve this, you will need to specify the java version you need maven to default to. So in my case, I needed java8.
Update /usr/local/Cellar/maven/3.5.4/bin/mvn
file as follows
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-$(/usr/libexec/java_home -v 1.8)}" exec "/usr/local/Cellar/maven/3.5.4/libexec/bin/mvn" "$@"
Paulo Merson
12.6k7 gold badges77 silver badges72 bronze badges
answered Mar 9, 2021 at 3:25
1
You just need to add your JAVA version to mvn file before the call of JAVA_HOME
for example my JAVA Version in .bashrc file is Java-17
and i want to run maven with Java-11 :
in file /usr/share/maven/bin/mvn
:
I add :
JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
before the call of JAVA_HOME
in the script
and then it works fine with Java-11
answered Jan 8, 2022 at 20:13
set JAVA_HOME=C:Program FilesJavajdk1.7.0_45jre
Adding the above line of code as the first statement in $MAVEN_HOMEbinmvn.cmd
worked for me straight away in Windows 10.
answered Jan 17, 2022 at 17:13
I couldn’t solve this problem with the answers above and I tried many things to solve this and I got it. I hope someone like me could solve the problem.
I am using brew to install java and maven.
For me, I wanted to use java 1.8. So I installed java 1.8
but still maven use version 17.0.2
Solution:
install java 1.8
I referred to this website to install it: https://devqa.io/brew-install-java/
mvn --version
and remember the version
cat /usr/local/Cellar/maven/VERSION(for me 3.8.5)/bin/mvn
Then you will see
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-/usr/local/opt/openjdk/libexec/openjdk.jdk/Contents/Home}" exec "/usr/local/Cellar/maven/3.8.5/libexec/bin/mvn" "$@"
Check this directory
ls /usr/local/opt
You will see files like openjdk, openjdk@17, openjdk@8
change the directory openjdk to openjdk@8 in mvn file:
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-/usr/local/opt/openjdk@8/libexec/openjdk.jdk/Contents/Home}" exec "/usr/local/Cellar/maven/3.8.5/libexec/bin/mvn" "$@"
answered Mar 30, 2022 at 3:04
Ondrej’s answer
worked perfectly. It truly solves the problem. Few other things to do though as detailed in the toolchain documentation
- Add the maven-toolchains-plugin in your project POM
- Configure the maven-toolchains-plugin to use a specific JDK in the toolchain as configured in your toolchains.xml file.
See sample configurations below:
toolchains.xml
<toolchains xmlns="http://maven.apache.org/TOOLCHAINS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/TOOLCHAINS/1.1.0 http://maven.apache.org/xsd/toolchains-1.1.0.xsd">
<!-- JDK toolchains -->
<toolchain>
<type>jdk</type>
<provides>
<version>1.8</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/Library/Java/JavaVirtualMachines/jdk1.8.0_301.jdk/Contents/Home</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>17</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>11</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/Library/Java/JavaVirtualMachines/jdk-11.0.12.jdk/Contents/Home</jdkHome>
</configuration>
</toolchain>
</toolchains>
As seen above, this works for machines having multiple java versions installed.
Then in the project’s POM, the maven-toolchains-plugin is configured to use one of the JDK versions defined as a toolchain.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-toolchains-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>toolchain</goal>
</goals>
</execution>
</executions>
<configuration>
<toolchains>
<jdk>
<version>11</version>
<vendor>sun</vendor>
</jdk>
</toolchains>
</configuration>
</plugin>
answered Apr 7, 2022 at 7:43
mikaelovimikaelovi
1014 silver badges10 bronze badges
Also you can have two versions of maven installed, and edit one of them, editing here:
mvn(non-windows)/mvn.bat/mvn.cmd(windows)
replacing your %java_home% appearances to your java desired path. Then just execute maven from that modified path
answered Dec 13, 2018 at 10:33
I’ve used the base idea from @Jonathan.
I’ve set the windows with: set JAVA_HOME=C:Program FilesjavaAdoptOpenJDK-11.0.8+10
call mvn clean package -DskipTests
answered Oct 9, 2020 at 0:01
GtdDevGtdDev
6805 silver badges12 bronze badges
I am using jenv and was facing the compilation error for «javax.xml.bind.annotation» as the mvn in terminal was using openjdk 13
Maven home: /usr/local/Cellar/maven/3.6.3_1/libexec
Java version: 13.0.2, vendor: N/A, runtime: /usr/local/Cellar/openjdk/13.0.2+8_2/libexec/openjdk.jdk/Contents/Home
For me, it worked after running ‘jenv enable-plugin maven’ as suggested here
https://stackoverflow.com/a/56487374/1582473
answered Apr 12, 2021 at 17:52
Mac Users,
If you have installed maven from HomeBrew(Brew),
Or even if you have installed it from elsewhere,
If you want to change the default version of the Java used by the Maven,
You can use following commands to change the version that the maven uses,
vim ~/.mavenrc
In the gui that pops up enter this and save-
JAVA_HOME="(put the Home path of your desired java version package)"
To verify wether the path is changed for maven you can check using —
mvn -v
answered Aug 24, 2022 at 7:14
Setting the Default Java Version
You might have 2 different versions of Java on your system. To set one as the default , use the command:
sudo alternatives ––config java
The system displays a list of different Java versions. If you like the default, press Enter.
If you want to change it, type the number of the version you want, then press Enter.
answered Sep 29, 2022 at 11:11
I am using MAC Mini — M1 chip, after installing maven through brew install maven I noticed it’s using java 19 but I rather wanted to use java 17 version that I downloaded in to my machine. Was out of luck with specific instructions to reset the default mvn java version. Here are the steps you can follow.
mvn --version
#this will give where the maven is installed
in my case Maven home:/opt/homebrew/Cellar/maven/3.8.7/libexec
- then go to
/opt/homebrew/Cellar/maven/3.8.7/bin
folder - edit mvn file, I used
vi mvn
- below I have edited the jdk location to point where I have java 17 jdk
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-/Library/Java/JavaVirtualMachines/jdk-17.0.3.1.jdk/Contents/Home}" exec "/opt/homebrew/Cellar/maven/3.8.7/libexec/bin/mvn" "$@"
- save the mvn file after edit
mvn -v
will now show it’s default java version is 17
Apache Maven 3.8.7 (b89d5959fcde851dcb1c8946a785a163f14e1e29)
Maven home: /opt/homebrew/Cellar/maven/3.8.7/libexec
Java version: 17.0.3.1, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk-17.0.3.1.jdk/Contents/Home
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "13.1", arch: "aarch64", family: "mac"
hamid
2,0074 gold badges21 silver badges42 bronze badges
answered Jan 28 at 23:26
Версии maven плагин изменить версию
После длительного изменения кода номер версии никогда не повышается, поэтому отдельные стабильные модули разработки не будут обновлять локально зависимые пакеты автоматически после обновления кода. Это также синхронизирует модификации ствола с веткой к другим ветвям.
Таким образом, в этом документе описывается, как использовать плагин maven версии для пакетного изменения номера версии каждого модуля проекта, гибкого продвижения или отката версии, предотвращения того, чтобы магистраль каждый раз обновляла код, и немедленно генерировать все ветви. воздействие.
-
maven среда сборки
-
Контроль версий
-
Введение параметра
-
Versions maven plugin
maven среда сборки
Установить maven
Установите maven super, всего четыре шага:
1. Загрузите Maven, который на самом деле является сжатым пакетом, распакуйте его
2. Настройте переменные среды
Существует две переменные среды, которые можно настроить:
MAVEN_HOME = D: maven apache-maven-3.2.3 (каталог maven)
MAVEN_OPTS = -Xms128m -Xmx512m (необязательно)
- 1
- 2
3. Добавьте «% MAVEN_HOME% bin;» в конец переменной пути.
Вышеуказанный MAVEN_HOME должен быть настроен. Если вы хотите, чтобы Maven работал быстрее, вы можете установить MAVEN_OPTS в соответствии с вашей ситуацией.
4. Наконец, убедитесь, что установка прошла успешно
Откройте cmd и введите:
mvn -v
- 1
Я думаю, что вы обязательно увидите некоторую информацию, как показано ниже:
Maven успешно установлен!
Контроль версий
Изменить полный номер версии модуля
При изменении версии,Вы должны стандартизировать запись файла pom.xml в модуле и явно объявить информацию о его родительском и дочернем узлах (<parent></parent>|<modules></modules>
), Вам нужно изменить номер версии всех модулей на 1.0.1-SNAPSHOT, вы можете находиться в корневом каталоге верхнего уровня, например, в стволе продукта под src, cmd, в корневой каталог, запустить команду:
mvn versions:set -DoldVersion=* -DnewVersion=1.0.1-SNAPSHOT -DprocessAllModules=true -DallowSnapshots=true
- 1
Введите после модификации:
mvn clean install -DskipTests
- 1
Maven начинает компиляцию и упаковку, пожалуйста, терпеливо подождите, после завершения компиляции проверьте, успешно ли скомпилирован результат
После успеха введите:
mvn dependency:tree -Dverboss -Dincludes=${project.groupId}:${project.artifactId}
- 1
Проверьте, все ли дерево зависимостей проекта зависит от базового модуля 1.0.1-SNAPSHOT:
Если все номера версий модуля изменены на: 1.0.1-SNAPSHAOT, изменение выполнено успешно.
Если модификация не удалась, используйте команду для отката номера версии:
mvn versions:revert
- 1
Чтобы подтвердить версию, вы можете использовать команду:
mvn versions:commit
- 1
Файл резервной копии, созданный измененной версией, будет автоматически удален.
Изменить версию модуля
Если вам необходимо увеличить номер версии модуля или если у вас возникли проблемы, вам нужно откатить версию модуля или региональное отделение хочет обновить модуль до новой версии, например, измените номер версии базового модуля на 1.0.1-SNAPSHOT, командная строка cmd для входа в модуль каталог.
Запустите команду:
mvn versions:set -DnewVersion=1.0.1-SNAPSHOT -DprocessAllModules=true -DallowSnapshots=true
- 1
Вы можете изменить модуль и номер версии, который зависит от модуля: 1.0.1-SNAPSHOT, где параметр -DallowSnapshots = true, что означает, что версия выпуска может быть изменена до версии моментального снимка.
С параметром -DprocessAllModules = true подмодули под модулем и номера версий, которые зависят от него, заменяются на 1.0.1-SNAPSHOT.
3.3 Изменить указанный номер версии модуля
Если вы хотите изменить номер версии указанного модуля, то есть номер версии, который зависит от него во всем модуле, например groupId:
Номер версии {артефакт} изменен на 1.0.2-SNAPSHOT, вы можете запустить команду:
mvn versions:set -DgroupId=${groupId} -DartifactId=${artifact} -DoldVersion=* -DnewVersion=1.0.2-SNAPSHOT -DallowSnapshots=true
- 1
Среди них artifactId, groupId и version формируют трехмерные координаты в maven, чтобы указать модуль, и указать здесь-DgroupId=${groupId} -DartifactId=${artifact}
Убедитесь, что модуль, который нужно изменить,${groupId}:${artifact}
。
Если вы не хотите изменять модуль, который зависит от mongodb, а также изменять номер версии mongodb, вы можете использовать параметр -DprocessDependencies = false, чтобы отменить изменение, которое зависит от него, тем самым изменяя только номер версии проекта xxx:
mvn versions:set -DgroupId=${groupId} -DartifactId=xxx -DoldVersion=* -DnewVersion=1.0.2-SNAPSHOT -DallowSnapshots=true -DprocessDependencies=false
- 1
Введение параметра
| Параметры | Значение по умолчанию | Описание |
|allowSnapshots |false
| Обновлять ли снимок версии снимка |
|artifactId |${project.artifactId}
| Указать artifactId |
|generateBackupPoms |true
| Резервное копирование файлов POM |
|groupId |${project.groupId}
| Указать groupId |
| newVersion | | Установить номер новой версии |
|nextSnapshot |false
| Обновленный номер версии — это номер версии следующего снимка |
|oldVersion |${project.version}
| Укажите номер версии, которую необходимо обновить, чтобы использовать значение по умолчанию ‘*’ |
|processAllModules |false
| Обновлять ли все модули в каталоге или объявлять родительские и дочерние узлы |
|processDependencies |true
| Обновление зависит от номера версии |
|processParent |true
| Обновлять ли номер версии родительского узла |
|processPlugins |true
| Обновлять ли номер версии в плагине |
|processProject |true
| Обновлять ли собственный номер версии модуля |
|removeSnapshot |false
| Удалите снимок версии снимка, чтобы сделать его стабильной версией выпуска |
|updateMatchingVersions |true
| Обновлять ли соответствующую версию, явно указанную в подмодуле (например, / project / version). |
Версии maven плагин
Для других случаев использования плагинов версий maven, пожалуйста, обратитесь к
http://www.mojohaus.org/versions-maven-plugin/index.html
- Details
- Written by
- Last Updated on 31 July 2021 | Print Email
In this short post, I’d like to share with you guys how to change Java version for a Maven project. Simply declare the following properties in the pom.xml file:
<project> [...] <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> [...] </project>
Then Maven will instruct Java compiler to compile source code against Java version 1.8, and generate .class files compatible with Java 1.8 as well. It’s equivalent to using the –source and –target flags of Java compiler (javac program).
Note that the source version must be equal to or less than the target version. Here’s another example:
<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>10</maven.compiler.target> </properties>
This will generate the .class files compatible with Java 10, with source code compatible to Java 8.
Alternatively, you can also change Java version for a Maven project by configuring the Maven compiler plugin as follows:
<project> [...] <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>11</source> <target>15</target> </configuration> </plugin> </plugins> </build> [...] </project>
This tells Java compiler to compile source code against Java version 11, and generate the .class files according to Java 15 format. If you want to use the same Java version for both source and target, use the <release> tag like this:
<configuration> <release>13</release> </configuration>
Change Java version for a multi-module Maven project:
In case you have a multi-module Maven project, the sub modules will inherit the compiler source and target settings from the parent project. But you can also override the settings in a specific module.
In Eclipse, you have to update the project for the changes to take effect. Right click on the project, click Maven > Update Project.
Change Java version for a Maven project in NetBeans IDE:
NetBeans automatically updates the change right after you save the pom.xml file. So you don’t have to do anything.
Change Java version for a Maven project in IntelliJ IDEA:
With IntelliJ IDEA, you may have to reload the Maven project by clicking the Refresh button in Maven view. Or right click on the project, then select Maven > Reload project.
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Add comment
In this quick guide, we discuss how to set specific java version in Maven configuration. There are several ways to tell Maven to which Java compiler version to use. Let’s discuss most commonly used options.
1. Default compiler version
With Maven, if you do not specify any compiler version explicitly, Maven uses Java 1.5 compiler version.
Before move on ahead, let’s understand how to compile java code in specific compiler version using JDK.
2. Understanding Compiling java code to specific version
2.1. javac
tool provides -source, -target and -bootclasspath options to compile Java code to specific version.
$ javac -help -source <release> Provide source compatibility with specified release -target <release> Generate class files for specific VM version -bootclasspath <path> Override location of bootstrap class files
-source
option verifies whether source code compatible with specified java release version.
-target
option compiles the source code to specified version.
Example: Suppose you have installed Java 8 in your machine, but you want to compile source code in 1.6.
$ javac MyTest.java -source 1.6 -target 1.6 -bootclasspath "%JAVA_HOME/jre/lib/rt.jar"
The above command successfully compiles source code against Java 1.6 version if the source code compatible with 1.6. If -bootclasspath not used, the source code do not compile correctly to the target version.
2.2. The above process works well until Java 8 version. In java 9 version, introduced a new option -release to support cross-compiler versions. -release option replaces three of these -source, -target and -bootclasspath
Java 9 and above versions, can be used single flag -release to compile source code to specific version.
Example: For example JDK 11 is installed in your machine, to compile against Java 8.
$ javac MyTest.java --release 8
Now let’s see the maven configuration options to set java version.
3. Java 8 and before versions
If you are using Higher version than Java 1.5, the version must be specified either using Maven project properties or by using Maven Compiler plugin.
3.1. Set version using properties
We can set the Java compiler version through the maven.compiler.source and maven.compiler.target properties. The source
and target
only valid 1.3, 1.4, 1.5 or 5, 1.6 or 6, 1.7 or 7, 1.8 or 8.
<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties>
3.2. Set version using plugin
We also can set the Java version using the source
and target
configuration options of Compiler Plugin. If we don’t set the source
and target
values, plugin takes 1.6 as the default version.
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin>
4. Java 9 and above versions
Java 9 and above versions, source code must be compatible with Java 1.5 or above. Means javac -source
does not support lower than 1.5 version. Valid Java versions to specify is 1.6, 6, 1.7, 7, 1.8 or 8, 9, 10 , 11 and 13.
As we discussed earlier, In java 9 version, a new option -release to support cross-compiler versions it replaces three of these -source, -target and -bootclasspath.
4.1. Set version using properties
We can set the Java compiler version through the maven.compiler.release. Make sure your plugin version must be 3.6 or above.
<properties> <maven.compiler.release>9</maven.compiler.release> </properties>
4.2. Set version using plugin
We can set the Java version by configuring the release
option of the Plugin.
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <release>8</release> </configuration> </plugin>
4.3. Additional compiler arguments
Sometimes for java newer versions, for example preview features, we may need to pass additional arguments to compiler to make it work. We can pass additional arguments to the compiler using compilerArgs option.
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <release>15</release> <compilerArgs>--enable-preview</compilerArgs> </configuration> </plugin>
5. Conclusion
In this quick guide, we learned how to set specific java version in Maven configuration.
You also might interested in following Maven guides:
- Install Maven on Windows
- Install Maven on Mac
- Install Maven on Ubuntu
- Import maven project into Eclipse
- Maven skip tests
- Maven run tests
- Maven run java main class
6. Reference
- Maven Document
- javac -bootclasspath
When running our Maven build, a member of my team gets a NoSuchMethodError in one of the dependant plug-ins when executing. However, when we run java -version
from her command line, it indicates Java 1.6.0_26. The error obviously seems to be screaming that Maven is using Java 5.
How do I figure out and change what version of Java is being used by Maven?
3 potentially important notes:
- This is executed at the command line, not using Eclipse plugin
- JAVA_HOME is set to a Java 1.6 JDK
- Using Maven 2.2.1
Laurel
5,90314 gold badges30 silver badges56 bronze badges
asked Aug 11, 2011 at 21:17
2
mvn -version
will output which java it’s using. If JAVA_HOME is set to a valid JDK directory and Maven is using something else, then most likely someone has tampered with the way that Maven starts up.
answered Aug 11, 2011 at 21:26
Ryan StewartRyan Stewart
124k20 gold badges178 silver badges196 bronze badges
1
You will need to configure maven-compiler-plugin
to use 1.6 source
and target
parameters ( by default it is 1.5 ).
This is the best done in your project’s parent pom in <pluginManagment>
section ( but you can always configure it per individual projects of course ).
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
answered Aug 11, 2011 at 23:25
mvn -version
tells you what compiler Maven is using, so this answers the question unless your POM specifies override values for the versions to be used.
Here’s the easiest way to specify the overrides in pom.xml
:
<properties>
<maven.compiler.target>1.9</maven.compiler.target>
<maven.compiler.source>1.9</maven.compiler.source>
</properties>
Alternatively, the maven-compiler-plugin
can be specified more explicitly. In that case, look at the <source>
and <target>
values associated with the plugin.
Both of these options are described here.
If your POM has a <parent>
, then you need to check that as well (recursively).
Note: When source
and target
are specified, these values are passed as command-line options to the compiler. Using this feature, you can compile or run against earlier Java versions than the compiler’s nominal value.
answered Sep 27, 2017 at 17:22
Brent BradburnBrent Bradburn
49.7k17 gold badges146 silver badges169 bronze badges
5
When running our Maven build, a member of my team gets a NoSuchMethodError in one of the dependant plug-ins when executing. However, when we run java -version
from her command line, it indicates Java 1.6.0_26. The error obviously seems to be screaming that Maven is using Java 5.
How do I figure out and change what version of Java is being used by Maven?
3 potentially important notes:
- This is executed at the command line, not using Eclipse plugin
- JAVA_HOME is set to a Java 1.6 JDK
- Using Maven 2.2.1
Laurel
5,90314 gold badges30 silver badges56 bronze badges
asked Aug 11, 2011 at 21:17
2
mvn -version
will output which java it’s using. If JAVA_HOME is set to a valid JDK directory and Maven is using something else, then most likely someone has tampered with the way that Maven starts up.
answered Aug 11, 2011 at 21:26
Ryan StewartRyan Stewart
124k20 gold badges178 silver badges196 bronze badges
1
You will need to configure maven-compiler-plugin
to use 1.6 source
and target
parameters ( by default it is 1.5 ).
This is the best done in your project’s parent pom in <pluginManagment>
section ( but you can always configure it per individual projects of course ).
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
answered Aug 11, 2011 at 23:25
mvn -version
tells you what compiler Maven is using, so this answers the question unless your POM specifies override values for the versions to be used.
Here’s the easiest way to specify the overrides in pom.xml
:
<properties>
<maven.compiler.target>1.9</maven.compiler.target>
<maven.compiler.source>1.9</maven.compiler.source>
</properties>
Alternatively, the maven-compiler-plugin
can be specified more explicitly. In that case, look at the <source>
and <target>
values associated with the plugin.
Both of these options are described here.
If your POM has a <parent>
, then you need to check that as well (recursively).
Note: When source
and target
are specified, these values are passed as command-line options to the compiler. Using this feature, you can compile or run against earlier Java versions than the compiler’s nominal value.
answered Sep 27, 2017 at 17:22
Brent BradburnBrent Bradburn
49.7k17 gold badges146 silver badges169 bronze badges
5