Maven setup in windows

В данной статье вы найдёте инструкцию по установке 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 Version

Если у вас выводится версия, значит, Maven готов к работе. Если нет, то убедитесь, что находитесь в директории bin, там есть файл mvn и выполнены требования перед установкой.

🏗️ Настройка PATH
#

Конечно, на данном этапе уже можно пользоваться Maven,
но придётся постоянно писать полный путь до файла mvn, и это неудобно.
Для того чтобы команда работала в любой директории,
необходимо добавить папку C:\apache-maven-3.8.6\bin
в системную переменную PATH. Это важная переменная, в ней перечислены
директории, в которых Windows ищет исполняемые файлы,
когда мы набираем в консоли имя файла.
Чтобы посмотреть её содержание, выполните команду в PowerShell:

echo $env:PATH

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.

По сути, мы склеиваем текущее значение с нашей директорией и записываем в эту же переменную.

set PATH

После выполнения команды закройте все терминалы и откройте заново.
Проверьте, что сохранилось в PATH echo $env:PATH.

Если путь до Maven есть в списке — время проверить работу команды mvn.

success PATH

Теперь вы можете запускать mvn в любой директории,
для этого вам не будет требоваться среда разработки.

🎉 Поздравляю с успешной установкой!

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.

How to install Maven on 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.

Click the binary zip archive link to download Maven

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.

Extract the Maven archive to an installation directory on your system

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.

Search for environment variables in the Start menu and open the first result

3. Under the Advanced tab in the System Properties window, click Environment Variables.

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.

Click the New button under the System variables section

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.

Enter the name and value of the new variable and click OK

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.

Select the Path system variable and click the Edit button

2. Click the New button in the Edit environment variable window.

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.

Add the path to the Maven directory and click OK

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.

Click the OK button to save 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
Check the current version of Maven to verify the installation

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

Last Updated :
04 Jan, 2025

Apache Maven is an automation tool. The tool is written in Java. It was initially released on 13 July 2004. It is developed by the Apache software foundation. It is part of the Jakarta Project. It is working on two aspects: how software is built, and its dependencies. It was created by Jason van Zyl. It is built by using a plugin-based architecture that allows it to make the use of any application controllable by standard input. It dynamically downloads Java libraries. 

How to Install Maven on Windows

Follow the below steps to install Apache Maven on Windows:

Step 1: Download Maven Zip File and Extract

opening-website

1. Click on the Download button.

clicking-download

2. Click on the apache-maven-3.8.4-bin.zip button.

clicking-apache-maven-3.8.4-bin.zip

3. Now check for the executable file in downloads in your system

4.  Now right-click on the file and click on extract here to extract the file.

5. After extracting, you get the extracted folder.

6. Now copy the extracted folder.

copying-extracted-folder

7.  Now paste the copy folder in your windows drive in the Program files folder.

pasting-folder

8. Now the Permission Windows appears to paste the folder in program files then click on “Continue”.

clicking-continue

9. Now open the folder apache maven.

opening-folder-apache-maven

10. Now after opening the folder then copy the address of the folder in program files.

copying-address

Step 2: Add MAVEN_HOME System Variable

1. Now click on Start Menu and search “Edit the system environment variables” and open it.

searching-edit-system-environment-variables

2. After opening System, Variable New window appears, and click on “Environment Variables…”

clicking-environment-variables

3. Now click on New under user variable.

selecting-new-under-user-variables

4. Now you can write any variable name and then paste the address we copy from program files in the variable value and then click on OK.

giving-variable-name

Step 3: Add MAVEN_HOME Directory in PATH Variable

1. Now go to the “System variables” Path option and double click on Path or Click on the Edit button.

editing-system-variables

2. Now click on New Button.

clicking-new-button

3. After New Paste the address we copy from program files to new.

pasting-address

4. After pasting the address add the \bin in the last and then click on OK.

adding-\bin

5. Now click on the OK button.

clicking-OK

6. Click on the OK button.

clicking-OK

Step 4: Verify Maven Installation

1.  Now your Apache Maven is installed on your computer. You may check by going to the “Start” menu typing Command Prompt. Open it.

checking-installed-apache-maven

2. When the Command Prompt opens, type mvn -version and click the enter button on the keyboard.

typing-mvn-version

3.  Now command prompt shows the version of Apache Maven installed on your windows.

Apache-maven-installed

You have successfully installed Apache Maven on your Windows 10 system.

How to Install Maven on Windows in Just 4 Easy Steps?

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.

Maven installation for Windows

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.

Apache-maven-3.8.4

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.

system properties

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.

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.

New system variable

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.

Environment Variables

2. From the editing environment variable window, select New.

editing environment

3. Fill out the new field with %MAVEN_HOME%bin. To save adjustments to the Path variable, hit OK.

Edit environment variable

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.

Environment Variables

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
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.

Learn to install Maven on a Windows operating system. In this maven installation guide, we are installing Maven on a Windows 11 machine. The steps are the same for a Windows 10 machine as well.

1. Windows Environmant Variables

Maven is a build and dependency management tool for Java applications development. Just like many other Java development tools, Maven is not installed as a Windows service, rather it is configured using the Windows environment variables.

Windows environment variables option

Windows environment variables option

2. Steps to Install and Configure Maven

Follow the steps needed to install maven on the windows operating system.

2.1. Verify Installed JDK and ‘JAVA_HOME’ Environment Variable

We must have Java installed on our computer and the JAVA_HOME must be set in the environment variables.

To install java, download JDK installer and install Java. Then add/update the JAVA_HOME variable to the JDK installation folder.

On my computer, JAVA_HOME is pointing to the JDK 17 installation folder.

JAVA_HOME Variable

2.2. Download and Extract Maven Zip File

We can download the latest version from Maven from the official website. Now we need to extract the downloaded zip file in any location.

I have extracted it on C:\devsetup\maven. You can choose your own folder location.

Maven Installation folder

Maven Installation folder

Let us briefly discuss what these directories contain:

  • The bin folder contains the batch files and shell scripts to run Maven on various platforms.
  • The boot folder contains the jars required for Maven to start.
  • The conf folder contains the default settings.xml file used by Maven.
  • The lib folder contains the libraries used by Maven. It also contains an ext folder in which third-party extensions, which can extend or override the default Maven implementation, can be placed.

2.3. Add M2_HOME Environment Variable

Now add the M2_HOME to windows environment variables. The value will be the installation location on your computer.

Note that it is an optional step, yet it is highly recommended. Many external IDEs and tools rely on M2_HOME variable to work with Maven.

Add M2_HOME Environment Variable

Add M2_HOME Environment Variable

2.4. Include ‘bin’ directory in PATH Variable

To run Maven commands from the console, windows should be able to locate the Maven batch files. Update the PATH variable with '%M2_HOME%\bin' directory.

Add Path to Maven bin folder

Add Path to Maven bin folder

3. Verify Maven Installation

Maven installation is complete. Now, let’s test it from the windows command prompt.

  1. Go to start menu and type cmd in application location search box.
  2. Press ENTER. A new command prompt will be opened.
  3. Type mvn -version in command prompt and hit ENTER.
$ mvn -version

The mvn command runs this batch file mvn.bat from bin folder of the Maven installation location. That’s why we added the the location to PATH environment variable.

After checking JAVA_HOME and any optional arguments (Maven_OPTS), the batch file runs its main class org.codehaus.plexus.classworlds.launcher.Launcher.

Verify Maven Installation

Verify Maven Installation

This should show the Maven version information, path to Maven bin folder and installed Java version.

If you face any error in the command prompt then please cross-check all the above steps.

Happy Learning !!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Internet explorer windows internet explorer 7 for windows 7
  • Empowering technology как убрать с экрана windows 10
  • Куда устанавливается криптопро windows
  • Как запустить hal dll windows
  • Как посмотреть железо на ноутбуке windows 10