Home > Back-end >  Maven insists JAVA_HOME is not defined correctly, unless I run it as sudo
Maven insists JAVA_HOME is not defined correctly, unless I run it as sudo

Time:10-08

Ubuntu 22.04.1, newly updated from 20.04.5.

When I try to build anything with Maven it complains:

$ mvn -v
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

I can get results with sudo, though:

$ sudo mvn -v
Apache Maven 3.6.3
Maven home: /usr/share/maven
Java version: 17.0.4, vendor: Private Build, runtime: /usr/lib/jvm/java-17-openjdk-amd64
Default locale: en_GB, platform encoding: UTF-8
OS name: "linux", version: "5.15.0-48-generic", arch: "amd64", family: "unix"

I could build fine last week before the update to Ubuntu 22.04; however when trying to build a new project my boss said I'd need to use sudo to build it, so I did. That failed due to Java versions (Maven was insisting on trying to use Java 8), and no matter what I did it wouldn't change to use 17. Until I just removed Java 8 entirely, at which point I started getting the JAVA_HOME is not defined correctly issue.

I've tried uninstalling all of the Java versions as well as Maven and reinstalling. My PATH and JAVA_HOME variables do seem to return correctly:

$ echo $JAVA_HOME
/usr/lib/jvm/java-17-openjdk-amd64
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin:/home/naf/.local/share/JetBrains/Toolbox/scripts:/usr/lib/jvm/java-17-openjdk-amd64/bin

I don't want to mess up projects by building as sudo, but I've no idea where to go with this.

CodePudding user response:

To have a correct installation of the Java Development Kit (JDK), it is best to install it via the system package manager and use the system tools to configure the active version. In Ubuntu packages of the JDK have names like: openjdk-xx-jdk, where xx is the version number. This command give you all available versions:

apt-cache search openjdk | grep -E ^openjdk-[0-9]*-jdk

Several version may be installed at the same time, do it with apt tool.

To check installed version:

sudo update-java-alternatives --list

To set active one:

sudo update-java-alternatives --set <tag_in_first_column_of_the_list>

If you do this properly, you won't have this problem anymore.

CodePudding user response:

JAVA_HOME is probably set in your own profile and then tested and dislikes by maven.

When switching to root that goes away so maven doesn’t do the test and can continue to just looking for java in the path.

To test run

unset JAVA_HOME; mvn … 

as you.

  • Related