What is the purpose of mvnw and mvnw.cmd files?
The mvnw and mvnw.cmd files are also known as maven wrappers. These files let you run maven builds without installing a maven distribution in your machine.
These files allow the users to have a fully encapsulated build system. So instead of setting up maven, PATH variables like M2_HOME, etc, the wrapper provides a self-contained build system.
How to use maven wrapper files?
Normally, you would need the following steps to run maven commands.
- Have java executable in your PATH or configure JAVA_HOME
- Download a Maven Distribution
- Unzip the maven distribution and keep it in a desired path
- add maven/bin directory to your PATH variable
Only then you can run
mvn clean package
But with the maven wrapper files, all you need to do is to run the following command.
On windows,
mvnw.cmd clean package
Code language: CSS (css)
On Linux and Mac,
./mvnw clean package
These commands behave the same way as mvn
commands without having to install Maven. Also, note that the executable scripts are different for windows and Linux for obvious reasons.
How to create mvnw mvnw.cmd files?
Most of the open-source projects come with these files out of the box. For example, Maven projects generated at Spring Initializer include mvnw and mvnw.cmd files. You can also see a “.mvn” directory which we will discuss in the upcoming sections.
But if you would like to add these files to your project, then the easiest way to do this is through maven itself (Yes, You need to have maven installed beforehand for this).
For this, you need to run the default wrapper goal from maven.
mvn wrapper:wrapper
Code language: CSS (css)
This goal creates the wrapper scripts in the root directory of the project and downloads maven-wrapper.jar under the .mvn/wrapper directory. It also creates a “.mvn/wrapper/maven-wrapper.properties
” file.
The content of the properties file contains the following.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
Code language: JavaScript (javascript)
So when you actually invoke the wrapper script, a maven distribution will be downloaded by the script, and then the maven command will be executed.
Configuring Maven versions
The wrapper goal can take a maven version parameter. Using this approach you could switch easily between different versions.
mvn wrapper:wrapper -Dmaven=3.8.4
Once the wrapper is created, you can also change the distribution version in the “.mvn/wrapper/maven-wrapper.properties” as well.
Summary
We learned what is maven wrapper files and how they help ease maven builds. Also, We learned how to create them ourselves and configure them as well