Last Updated :
17 Sep, 2024
Apache Maven is a comprehensive build automation tool widely used for managing and building Java projects. It simplifies the process of managing project dependencies and building projects through a standardized approach. This article provides step-by-step instructions to install Apache Maven on Windows, macOS, and Linux.
What is Maven?
Maven is a build automation tool that focuses on two main areas:
- Building Software: Maven uses a plugin-based architecture to manage the build process of software projects.
- Handling Dependencies: Maven automatically manages and downloads Java libraries needed for the project.
If you would like to install Apache Maven in operating systems such as Windows, macOS, or Linux, please take a look at the steps mentioned below.
Install Apache Maven on macOS
We need to follow the steps mentioned below to install apache maven in the macOS.
Step 1: Open Maven Website
First step is to open the maven website, simply type apache maven download in search engine and open the first website which will look similar to image below.
Step 2: Download the latest binary zip archive
Once you open the website, scroll and select the following file for downloading, this is the file that contains the apache maven for macOS.
Step 3: Extract the Zip File
Locate the downloaded zip file and double-click it to extract. It will create a new folder with the same name as the zip file.
Step 4: Open Environmental Path
Next step is to open the environmental path and for configuring the environment variable. We will have to open it in the terminal. For this, simply launch a terminal in macOS and type the following command to open the environmental path:
vi .zshenv
Step 5: Configure Environment Variable
Once we have opened the environmental path, we will have to configure it by adding the path where the maven folder is stored and update the BIN location (path and folder name can vary in your case).
Here is my location and path for example:
export M2_HOME="$PATH:/Users/prashantrana/Documents/Dev/JavaSpring/apache-maven-3.6.3"
export PATH=$PATH:$M2_HOME/bin
Once you save this location of the environmental path, maven is ready to be used in your macOS operating system.
After this, you can verify the installation by using the below command:
mvn -version
This will display the Maven version installed on your system. This is how apache maven can be installed and configured in macOS system.
Install Apache Maven on Windows
For installing apache maven on the Windows operating system, we already have a dedicated article that you can follow, it involves several steps for installing Apache Maven on Windows.
How to Install Apache Maven on Windows?
Install Apache Maven on Linux
For installing apache maven on Linux, we will have to follow the below steps one by one.
Step 1: Verify JDK Installation
First step is to verify whether JDK is installed or not. For this, simply open a terminal and type the following command:
java --version
After typing this command you can see output similar to image below, if it is not installed properly then it will show an error message that command was not found.
If you need to install JDK in Linux you can read this article: How to Install JDK in Linux?
Once it is verified that JDK is installed, go to the next step.
Step 2: Update Package Index
Next step is to update the library. This step is also important because we need to make sure we can run the command for installing maven and for that directory list needs to have maven in it.
Type the following command in your terminal and wait until the list is downloaded:
sudo apt update
Step 3: Install Maven
Next step is to install maven. For this, simply type the following command and it will install maven in the Linux system.
sudo apt install maven
As you can see in the image below as well:
Step 4: Verify Maven Installation
Once the installation is completed, we can check whether maven is installed successfully or not. For checking this, we will have to enter the following command in the linux terminal.
mvn -version
This will show us the maven version which is installed in the system, also seen in the image below as well.
This will display the Maven version installed on your system. This is how we can install maven in different operating systems.
Conclusion
Apache Maven is a robust tool for managing project builds and dependencies. Installing Maven varies by operating system, but the process is straightforward. Follow the steps outlined above for Windows, macOS, or Linux to get Maven up and running on your system.
Apache Maven is a build-automation tool designed to provide a comprehensive and easy-to-use way of developing Java applications. It uses a POM (Project Object Model) approach to create a standardized development environment for multiple teams.
In this tutorial, we will show you how to install Apache Maven on a system running Windows.
Prerequisites
- A system running Windows.
- A working Internet connection.
- Access to an account with administrator privileges.
- Access to the command prompt.
- A copy of Java installed and ready to use, with the JAVA_HOME environment variable set up (learn how to set up the JAVA_HOME environment variable in our guide to installing Java on Windows).
How to Install Maven on Windows
Follow the steps outlined below to install Apache Maven on Windows.
Step 1: Download Maven Zip File and Extract
1. Visit the Maven download page and download the version of Maven you want to install. The Files section contains the archives of the latest version. Access earlier versions using the archives link in the Previous Releases section.
2. Click on the appropriate link to download the binary zip archive of the latest version of Maven. As of the time of writing this tutorial, that is version 3.8.4.
3. Since there is no installation process, extract the Maven archive to a directory of your choice once the download is complete. For this tutorial, we are using C:\Program Files\Maven\apache-maven-3.8.4.
Step 2: Add MAVEN_HOME System Variable
1. Open the Start menu and search for environment variables.
2. Click the Edit the system environment variables result.
3. Under the Advanced tab in the System Properties window, click Environment Variables.
4. Click the New button under the System variables section to add a new system environment variable.
5. Enter MAVEN_HOME as the variable name and the path to the Maven directory as the variable value. Click OK to save the new system variable.
Step 3: Add MAVEN_HOME Directory in PATH Variable
1. Select the Path variable under the System variables section in the Environment Variables window. Click the Edit button to edit the variable.
2. Click the New button in the Edit environment variable window.
3. Enter %MAVEN_HOME%\bin in the new field. Click OK to save changes to the Path variable.
Note: Not adding the path to the Maven home directory to the Path variable causes the 'mvn' is not recognized as an internal or external command, operable program or batch file
error when using the mvn
command.
4. Click OK in the Environment Variables window to save the changes to the system variables.
Step 4: Verify Maven Installation
In the command prompt, use the following command to verify the installation by checking the current version of Maven:
mvn -version
Conclusion
After reading this tutorial, you should have a copy of Maven installed and ready to use on your Windows system.
Was this article helpful?
YesNo
В данной статье вы найдёте инструкцию по установке Maven из архива,
настройке переменных окружения для возможности запуска команд Maven
в командной строке операционной системы Windows.
Требования
#
Предварительно у вас должен быть установлен JDK версии не ниже 8 и настроена
переменная окружения $JAVA_HOME
. Проверьте в PowerShell
командами java --version
и echo $env:JAVA_HOME
. На скриншоте пример вывода,
который удовлетворяет дальнейшим действиям.
Если у вас ошибки и команда java не найдена, а JAVA_HOME ничего не выводит, скачайте
и установите JDK.
На странице необходимо выбрать операционную систему,
скачать файл MSI и запустить.
Это обычный установщик, в котором достаточно будет нажать «Далее».
После установки закройте все окна PowerShell и откройте заново,
попробуйте выполнить команды. Перезагрузку тоже можете попробовать 🙂
⏬ Скачивание архива
#
Перейдите на официальный сайт проекта Maven и скачайте архив
Downloading Apache Maven
На странице найдите секцию Files и скачайте Binary Zip Archive.
📤 Распаковка архива
#
Найдите файл со скачанным архивом. Нажмите на него правой клавишей мыши
и выберите «Извлечь всё…» (Extract All…).
В предложенном окне установите путь, куда будет распакован архив. Вы можете распаковать в удобное для вас место. При этом в пути не должно быть пробелов, кириллицы или специальных символов.
В примере будем устанавливать в корень диска C:\
, можете вписать или
выбрать через кнопку «Обзор…» (Browse…).
Нажмите кнопку «Распаковать» (Extract).
☑️ Проверка запуска
#
Содержимое архива представляет собой набор библиотек и исполняемых файлов.
Мы можем попробовать его запустить. Для этого откройте командную строку
(Windows PowerShell) и перейдите в директорию, в которую распаковали архив.
Если распаковали в C:, то команда будет cd C:\
Далее посмотрите список файлов и найдите директорию apache-maven-3.x.x
.
У вас версия может отличаться, так как Maven активно обновляется.
В примере это директория apache-maven-3.8.6
.
Перейдите в директорию apache-maven-3.8.6
и далее в директорию bin
. Это можно сделать одной командой:
cd C:\apache-maven-3.8.6\bin
Выполните команду ./mvn -version
. Если переменная окружения JAVA_HOME ведёт на JDK, то вы увидите версию Maven:
Если у вас выводится версия, значит, Maven готов к работе. Если нет, то убедитесь, что находитесь в директории bin, там есть файл mvn и выполнены требования перед установкой.
🏗️ Настройка PATH
#
Конечно, на данном этапе уже можно пользоваться Maven,
но придётся постоянно писать полный путь до файла mvn, и это неудобно.
Для того чтобы команда работала в любой директории,
необходимо добавить папку C:\apache-maven-3.8.6\bin
в системную переменную PATH
. Это важная переменная, в ней перечислены
директории, в которых Windows ищет исполняемые файлы,
когда мы набираем в консоли имя файла.
Чтобы посмотреть её содержание, выполните команду в PowerShell:
echo $env:PATH
В результате будет выведена строка с директориями, разделёнными точкой с запятой.
Как это работает?
Например, если мы в терминале наберём команду calc
, откроется приложение
«Калькулятор». Так как операционная система прошлась по очереди по всем папкам
и нашла в одной из них приложение calc.exe
, его и запустила.
Операционная система всегда запускает первый попавшийся подходящий
исполняемый файл, даже если их несколько в разных директориях.
Таким же образом директории проходятся по очереди записи в строке PATH.
Это значит, что нам надо добавить в этот список и папку с исполняемым файлом mvn.
Сделайте это из консоли. Только на всякий случай сохраните в текстовый файл
все директории, которые получили командой echo $env:PATH
.
Если вы ошибётесь в команде и удалите данные, то сможете восстановить их
из файла. Чтобы сохранить сразу в файл, используйте команду
$env:PATH >> path.txt
. Значение сохранится в папке, в которой вы находитесь.
Команда для добавления директории bin:
setx PATH "$env:PATH;C:\apache-maven-3.8.6\bin"
❗ Не ставьте в конце пути \ (обратный слеш), так как это будет экранировать кавычку, и кавычка станет частью строки.
Эта команда записывает в PATH
cамо значение PATH
и добавляет нашу строку. Важно на забыть поставить разделитель ; в начале нашего пути до bin.
По сути, мы склеиваем текущее значение с нашей директорией и записываем в эту же переменную.
После выполнения команды закройте все терминалы и откройте заново.
Проверьте, что сохранилось в PATH echo $env:PATH
.
Если путь до Maven есть в списке — время проверить работу команды mvn.
Теперь вы можете запускать mvn в любой директории,
для этого вам не будет требоваться среда разработки.
🎉 Поздравляю с успешной установкой!
Apache Maven is a project build automation and dependency management tool widely used in Java development. It streamlines the development process by simplifying project setup, library management, and build execution. If you are a Java developer on Windows setting up Maven is important to leverage its capabilities.
This guide will walk you through the installation process on how to install Maven WIndows ensuring a smooth and successful experience in automation infrastructure.
Prerequisites
Before diving into the installation process make sure you have the following on your Windows machine:
- Maven relies on Java for execution. Download and install the latest JDK version from the official Oracle website. Further, you can also refer to our guide on how to install Java on Windows system.
- Modifying system environment variables requires administrative privileges. Make sure you are logged in with an account that has admin rights.
Installing Maven on Windows
Verify the Java installation by opening a command prompt and typing the following command:
Java --version
If successful you will see the installed Java version details.
To download Maven Windows, Head over to the official Maven download page. Locate the Binary distribution section and download the appropriate archive file. The latest stable version is recommended for most users.
Use a decompression tool like 7-Zip to extract the downloaded archive file. You can choose any convenient location on your system for extraction.
Environment variables are system-level settings that control how programs access resources. In order to configure Maven we need to set the environment variables:
1. MAVEN_HOME: This points to the directory where you extracted the Maven archive. For example, it would be C:\apache-maven-3.x.x
2. PATH: This variable defines the search path for executable files. We need to add the bin
directory within the Maven installation directory to the PATH. For example, it would be C:\apache-maven-3.x.x\bin
.
Setting Up Environment Variables
Right-click on “This PC” and select the “Properties” option then Click on “Advanced system settings” in the left-hand panel. In the “System Properties” window, go to the “Advanced” tab and click on the “Environment Variables” button. Another option is to type environment variables in the search bar.
Under “System variables,” find the variable named “Path” and click “Edit.”
In the “Edit environment variable” window, click “New” to add a new entry. Paste the path to your Maven’s bin
directory for example C:\apache-maven-3.x.x\bin
and click “OK.” Click “OK” on all open windows to save the changes.
Open a new command prompt window. Type the following command and press Enter.
mvn -v
If the installation was successful you should see an output displaying the installed Maven version information.
Install Maven on Our Best Java Hosting!
Enhance your applications with our Ultahost Java hosting solutions. Enjoy unmatched flexibility, infinite scalability, and exceptional performance at a competitive price.
Troubleshooting
Following are some troubleshooting if you encounter issues during the installation of Maven on Windows system:
- If the Maven version command doesn’t work double-check that you’ve added the correct path to the
MAVEN_HOME\bin
directory in your system environment variables. Typos or incorrect paths can lead to issues. - Make sure you have Java installed and accessible from the command prompt. Verify the installation by running in the command prompt. If it fails revisit the Java installation steps.
- Make sure you are logged in with an administrator account when modifying environment variables.
Why We Need Maven
With Maven in place, you can increase capabilities for your Java projects. Here’s a glimpse into what you can achieve:
- Project Management: Maven provides a standardized directory structure for your project making it easy to organize source code, resources, and configuration files.
- Dependency Management: Maven eliminates the need to manually download and manage third-party libraries. It retrieves dependencies from remote repositories based on declarations in your project’s
pom.xml
file. This centralizes library management and ensures consistency across projects. - Build Automation: Maven allows you to define build lifecycles with various phases like compiling, testing, packaging, and deployment. These phases can be triggered with a single command, streamlining the build process.
- Reproducibility: Maven builds are repeatable. Regardless of the development environment executing the Maven commands will produce consistent results ensuring project builds are reliable and predictable.
Additional Notes
Following are some additional notes after installing Maven for Windows 10 operating system:
- While working with Maven you will likely interact with project configuration files. Consider using a good text editor like Notepad++ or Sublime Text for editing these files.
- Popular IDEs like IntelliJ IDEA and Eclipse provide plugins for Maven integration. These plugins offer functionalities like project creation, build execution, and dependency management directly from within the IDE.
- New Maven versions are released periodically with bug fixes and improvements. It’s recommended to check for updates occasionally and follow the same download and installation steps to upgrade to the latest version.
Conclusion
By following the instructions in this guide, you have successfully installed Apache Maven on your Windows system. With Maven in place, you can streamline your Java development workflow. You can benefit from its project management tools and dependency management skills with build automation functionalities to increase efficiency and maintain consistency across your projects.
Installing Maven on Windows is simple but it can be tricky to manage different Maven versions or ensure compatibility for specific applications. Upgrading to an Ultahost Windows VPS empowers you with greater control and flexibility. These plans grant you access allowing you to install and manage multiple Maven versions using tools avoiding conflicts or compatibility issues.
FAQ
What is Maven?
Maven is a build automation tool used primarily for Java projects.
Where can I download Maven?
You can download Maven from the official Apache Maven website.
Do I need Java installed before Maven?
Yes, you need to have Java installed on your system before installing Maven.
How do I set up the environment variables for Maven?
Add the Maven bin directory to the PATH environment variable in your system settings.
How can I verify Maven is installed correctly?
Open a command prompt and type the Maven version command to check if Maven is installed and configured properly.
Introduction
Tools for automation include Apache Maven installation. Java was used to create the tool. On July 13, 2004, it had its debut release. The Apache Software Foundation is the one who created it. It is a component of the Jakarta Project. Both the dependencies of software and how it gets constructed are currently being worked on. Jason van Zyl was the person who came up with it. Its architecture depends on plugins, enabling conventional input to be used to control any application. Java libraries get downloaded dynamically.
An all-inclusive and user-friendly method of creating Java applications is offered by the build-automation tool Apache Maven. A consistent development environment for numerous teams is produced using a POM (Project Object Model) methodology.
We’ll demonstrate how to install Maven on Windows-based PCs in the following article.
System Requirements
You’ll require
- a Windows-based computer.
- an active Internet connection.
- the ability to get into an account with administrative rights.
- using the command prompt.
- a functioning Java installation with the JAVA_HOME environment parameter set
Download Maven on Windows and Extract it from the Zip File
1. Go to the Maven download website and install the Maven version on Windows you want to use. The most recent version’s archives are located in the Files section. Utilize the archives option in the Previous Releases section to access earlier releases.
2. Select the appropriate link to download the binary zip bundle of the most recent Maven installation for Windows. At the time this guide was being written, that was version 3.8.4.
3. Following the successful install Maven on Windows, extract it to a directory of your choice because there is no setup procedure. Install Apache-maven-3.8.4 is the version of Maven on Windows. we are using for this course of study.
Add MAVEN_HOME and JAVA_HOME System Variable
1. Click on Start, then type “environment variables” into the search bar.
2. Select the system environment variables outcome and click Edit.
3. Select Environment Variables from the list of options on the Advanced tab of the System Properties window.
4. select the New button beneath the System Variables section to add a new system environment variable.
5. Type MAVEN_HOME as the parameter name and the Maven directory path as the variable value. For the newly created system variable to get saved, hit OK.
Also Read: How to Enable or Install Telnet on Windows 10 or 11?
Add MAVEN_HOME Path in the Environment Variable
1. Choose the Path variable From the Environment Variables window’s System variables component. The variable can be changed by clicking the Edit button.
2. From the editing environment variable window, select New.
3. Fill out the new field with %MAVEN_HOME%bin. To save adjustments to the Path variable, hit OK.
Keep in mind that While using the mvn command, the error’mvn’ is not recognized as an external or internal command, executable program, or batch file will occur if the path for the Maven home directory is not included in the Path variable.
4. Select OK in the Environment Variables box to save the system variable adjustments.
Verify Maven Installation
To confirm that the installation succeeded by examining the most recent Maven version in Windows, enter the next command from the command prompt:
mvn -version
Also Read: How to Update Git Version on Linux, Windows, Mac?
Conclusion
Your Windows computer has now been effectively configured to install Apache Maven.
Once you’ve finished reading this article, Maven should be downloaded and prepared for your Windows computer.
He is the Director of Cloud Operations at Serverwala and also follows a passion to break complex tech topics into practical and easy-to-understand articles. He loves to write about Web Hosting, Software, Virtualization, Cloud Computing, and much more.