使用 Maven 时遇到的一个小问题

之前在 MacOS 的命令行中使用 Maven 时,遇到 mvn compile 报错,说我的 $JAVA_HOME 环境变量没有正确设置:

1
2
3
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

于是我打开了 .zshrc 文件,我的 $JAVA_HOME 是这样写的;

1
2
3
export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/bin:$PATH
export CLASS_PATH=$JAVA_HOME/lib

之所以写成 export JAVA_HOME=$(/usr/libexec/java_home),是因为我之前在网上查找如何设置 MacOS 的 $JAVA_HOME,看到了这么一段话:

Many Java applications need to know the location of a $JAVA_HOME directory. The $JAVA_HOME on Mac OS X should be found using the /usr/libexec/java_home command line tool on Mac OS X 10.5 or later. On older Mac OS X versions where the tool does not exist, use the fixed path “/Library/Java/Home”. The /usr/libexec/java_home tool dynamically finds the top Java version specified in Java Preferences for the current user. This path allows access to the bin subdirectory where command line tools such as java, javac, etc. exist as on other platforms. The tool /usr/libexec/java_home allows you to specify a particular CPU architecture and Java platform version when locating a $JAVA_HOME.

Another advantage of dynamically finding this path, as opposed to hardcoding the fixed endpoint, is that it is updated when a new version of Java is downloaded via Software Update or installed with a newer version of Mac OS X. For this reason, it is important that developers do not install files in the JDKs inside of /System, since the changes will be lost with subsequent updates by newer versions of Java.

To obtain the path to the currently executing $JAVA_HOME, use the java.home System property.

大意就是说,/usr/libexec/java_home 这个命令会直接找到本机上版本最新的 Java 的 $JAVA_HOME,所以我就直接写成了上面 .zshrc 文件的样子,结果 Maven 却报错,说我写得不对。于是我直接输入命令:

1
$ /usr/libexec/java_home

得到的结果却是:

1
/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

问题在于,这个/Library/Internet Plug-Ins/目录的 Internet Plug-Ins 中间有一个空格,所以如果直接把这一串写进 .zshrc 文件的话,没有转义,就会导致路径不对。

至于为什么 Java 会安装在这个目录下呢,原来这是 MacOS 使用 .dmg 方式安装的 Java。我找到我另一个 Java 版本的 Home 目录,在 /Library/Java/JavaVirtualMachines/jdk1.8.0_271.jdk/Contents/Home 下,于是我把 $JAVA_HOME 改成该路径,问题就解决了。

Author: birdkyle7918
Link: https://birdkyle7918.com/2021/04/30/使用-Maven-时遇到的一个小问题/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
请我喝杯咖啡(支付宝)