Улучшение Maven проектов
В течение долгого времени Maven был инструментом сборки defacto и управления зависимостями для проектов Java. Плагины добавили некоторые интересные вещи, но теперь Maven пополнился новыми функциями, улучшающими другие:
- Maven Lifecycle
- Мавен Полиглот
- Maven Wrapper
Все эти новые функции благодаря Такири , который возглавляет Джейсон ван Зил ( @jvanzyl ), отец Maven.
Maven Lifecycle
Избегайте повторной компиляции, если в исходном коде нет изменений. Вам просто нужно выполнить два простых шага, чтобы включить эту удивительную функцию. Экономьте свое время!
1. Добавьте плагин ниже:
io.takari.maven.plugins takari-lifecycle-plugin true
2. Переключите ваш ток packaging с jar на takari-jar .
В журнале видно, что плагин вступил в силу. Теперь, если вы уже скомпилировали, вам не придется снова компилировать, если вы не внесете изменения в свой исходный код.
Мавен Полиглот
Создание pom файла в формате XML является многословным. Теперь вы можете создавать свой pom на разных языках: Atom, Clojure, Groovy, Ruby, Scala, Yaml. И воспользоваться каждым из них.
- Внутри проекта создайте .mvn/extensions.xml файл, где будет иметь место языковая зависимость:
Атом:
io.takari.polyglot polyglot-atom 0.1.6
Clojure:
io.takari.polyglot polyglot-clojure 0.1.6
Groovy:
io.takari.polyglot polyglot-groovy 0.1.6
Рубин:
io.takari.polyglot polyglot-ruby 0.1.6
Scala:
io.takari.polyglot polyglot-scala 0.1.6
YAML:
io.takari.polyglot polyglot-yaml 0.1.6
Вы хотите перенести xml на любой другой язык? Вы можете сделать это, выполнив команду ниже:
mvn io.takari.polyglot:polyglot-translate-plugin:translate -Dinput=pom.xml -Doutput=pom.
Где format может быть atom , clj , groovy , rb , scala и yml .
Maven Wrapper
Совместное использование проектов является распространенным явлением, и иногда у нас есть конкретные версии из нашего инструмента сборки Теперь вам не нужно спрашивать вашего друга, какая версия maven вам нужна, если используется проект maven maven-wrapper . Для этого вам просто нужно запустить:
mvn -N io.takari:maven:wrapper
Теперь вы можете сделать сборку mvnw clean install . Если вы хотите посмотреть, какую версию Maven вы скачаете, загляните .mvn/wrapper/maven-wrapper.properties внутрь своего проекта.
Maven Wrapper
The Maven Wrapper is an easy way to ensure a user of your Maven build has everything necessary to run your Maven build.
Why might this be necessary? Maven to date has been very stable for users, is available on most systems or is easy to procure: but with many of the recent changes in Maven it will be easier for users to have a fully encapsulated build setup provided by the project. With the Maven Wrapper, this is very easy to do and it’s a great idea and initial implementation borrowed from Gradle.
The easiest way to setup the Maven Wrapper for your project is to use the Maven Wrapper Plugin with its provided wrapper goal. To add or update all the necessary Maven Wrapper files to your project execute the following command:
mvn wrapper:wrapper
Normally you instruct users to install a specific version of Apache Maven, put it on the PATH and then run the mvn command like the following:
mvn clean install
But now, with a Maven Wrapper setup, you can instruct users to run wrapper scripts:
./mvnw clean install
mvnw.cmd clean install
A normal Maven build will be executed, with the one important change that if the user doesn’t have the necessary version of Maven specified in .mvn/wrapper/maven-wrapper.properties it will be downloaded for the user first, installed and then used.
Subsequent uses of mvnw / mvnw.cmd use the previously downloaded, specific version as needed.
Supported Systems
The wrapper should work on various operating systems including
- Linux (numerous versions, tested on Ubuntu and CentOS)
- OSX / macOS
- Windows (various newer versions)
- Solaris (10 and 11)
- BSD
A POSIX-compatible Bourne shell is required to run the wrapper script.
In terms of Apache Maven versions itself, the wrapper should work with any Maven 3.x version and it defaults to the release used when setting up the wrapper. We do NOT plan to support the deprecated, EOL’ed Maven 2.x.
The maven-wrapper.jar (to download and install target Maven version required by mvnw ) and the Maven Wrapper Plugin (to inject Wrapper into a project) use Java 7.
Verbose Mode
The wrapper supports a verbose mode in which it outputs further information. It is activated by setting the MVNW_VERBOSE environment variable to true .
By default it is off.
Usage without Binary JAR
By default, the Maven Wrapper JAR archive is added to the using project as small binary file .mvn/wrapper/maven-wrapper.jar . It is used to bootstrap the download and invocation of Maven from the wrapper shell scripts.
If your project is not allowed to contain binary files like this, you can use the source distribution of the maven wrapper which adds a file .mvn/wrapper/MavenWrapperDownloader.java file instead:
# defaults to bin mvn wrapper:wrapper -Dtype=source
You can also chose to opt out of all additional resources except the wrapper scripts:
mvn wrapper:wrapper -Dtype=script
Another type is the lite implementation of mvnw / mvnw.cmd scripts which download the maven directly via wget or curl on *nix, or PowerShell on Windows, then call the original mvn / mvn.cmd scripts of the downloaded maven distribution. This type does not use maven-wrapper.jar nor MavenWrapperDownloader.java , only the wrapper scripts are required.
mvn wrapper:wrapper -Dtype=only-script
If the JAR is not found to be available by the scripts they will attempt to download the file from the URL specified in .mvn/wrapper/maven-wrapper.properties under wrapperUrl and put it in place. The download is attempted via curl, wget and, as last resort, by compiling the .mvn/wrapper/MavenWrapperDownloader.java file and executing the resulting class.
If your Maven repository is password protected you can specify your username via the environment variable MVNW_USERNAME and the password via the environment variable MVNW_PASSWORD .
Using a Different Version of Maven
To switch the version of Maven used to build a project, you can initialize it using:
mvn wrapper:wrapper -Dmaven=3.5.4
which works for any version except snapshots. Once you have a wrapper you can change its version by setting the distributionUrl in .mvn/wrapper/maven-wrapper.properties , e.g.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip
Using Basic Authentication for Distribution Download
To download Maven from a location that requires Basic Authentication you have 2 options:
- Set the environment variables MVNW_USERNAME and MVNW_PASSWORD or
- add user and password to the distributionUrl like that: distributionUrl=https://username:password@/maven2/org/apache/maven/apache-maven/3.2.1/apache-maven-3.2.1-bin.zip
Specifying Maven Distribution Base Path
This is a feature of Maven itself and the wrapper just happens to take it into account. Simply set MAVEN_USER_HOME to the desired path and the wrapper uses it as the base of the Maven distro installation.
Using a Maven Repository Manager
When using an internal Maven repository manager, you have two options:
- Just set the correct URL to wrapper jar and Maven distro in maven-wrapper.properties in your project
- Leave the default URL in the project pointing to Maven Central and set the environment variable MVNW_REPOURL to your repo manager URL such as https://repo.example.com/central-repo-proxy .
If MVNW_REPOURL is set during the wrapper installation with the maven-wrapper-plugin, the URL is used in the maven-wrapper.properties file.
If not set, but your mirror URL in your settings.xml is configured, it will be used.
Checksum verification of downloaded binaries
To avoid supply-chain-attacks by downloading a corrupted artifact, it is possible to specify checksums for both the maven-wrapper.jar and the downloaded distribution. To apply verification, add the expected file’s SHA-256 sum in hex notation, using only small caps, to maven-wrapper.properties . The property for validating the maven-wrapper.jar file is named wrapperSha256Sum whereas the distribution file property is named distributionSha256Sum .
Internals
Maven Wrapper is composed of 3 pieces:
- maven-wrapper, providing the maven-wrapper.jar that downloads, installs and runs target Maven distribution,
- maven-wrapper-distribution, that provides mvnw / mvnw.cmd scripts distributions,
- maven-wrapper-plugin, the wrapper plugin to ease installing Wrapper into a project.
What is the purpose of mvnw and mvnw.cmd files?
When I created a Spring Boot application I could see mvnw and mvnw.cmd files in the root of the project. What is the purpose of these two files?
13.1k 8 8 gold badges 47 47 silver badges 77 77 bronze badges
asked Aug 2, 2016 at 14:53
shaunthomas999 shaunthomas999
5,614 2 2 gold badges 27 27 silver badges 30 30 bronze badges
6 Answers 6
These files are from Maven wrapper. It works similarly to the Gradle wrapper.
This allows you to run the Maven project without having Maven installed and present on the path. It downloads the correct Maven version if it’s not found (as far as I know by default in your user home directory).
The mvnw file is for Linux (bash) and the mvnw.cmd is for the Windows environment.
To create or update all necessary Maven Wrapper files execute the following command:
mvn -N io.takari:maven:wrapper
To use a different version of maven you can specify the version as follows:
mvn -N io.takari:maven:wrapper -Dmaven=3.3.3
Both commands require maven on PATH (add the path to maven bin to Path on System Variables) if you already have mvnw in your project you can use ./mvnw instead of mvn in the commands.
5,214 3 3 gold badges 51 51 silver badges 67 67 bronze badges
answered Aug 2, 2016 at 14:57
8,097 2 2 gold badges 31 31 silver badges 45 45 bronze badges
Thanks for the answer. Can you explain when this gets generated, like is it when you initially create a project? Will it gets updated along the line when you do changes to your pom like add remove dependencies/plugins ?
Sep 20, 2017 at 23:20
and, should you add/commit the mvnw.cmd files?
Jan 15, 2019 at 3:26
yes, of course. it allows you to quickly run your maven build without the need to extra install maven or having it on PATH.
Jan 15, 2019 at 19:04
So many thanks for the answer, it’s very helpful ¿Could you tell us something about the portability of the maven settings files when we working in that way? Saludos and thanks again.
Sep 13, 2019 at 4:49
@DanielHernández the maven wrapper uses the default settings.xml on the users system. and according to this issue there are some tricks how you could add a custom settings.xml to the repo but it seems then it ignores the user settings on system.
Sep 13, 2019 at 6:30
Command mvnw uses Maven that is by default downloaded to ~/.m2/wrapper on the first use.
URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties :
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
To update or change Maven version invoke the following (remember about —non-recursive for multi-module projects):
./mvnw io.takari:maven:wrapper -Dmaven=3.3.9
or just modify .mvn/wrapper/maven-wrapper.properties manually.
To generate wrapper from scratch using Maven (you need to have it already in PATH run:
mvn io.takari:maven:wrapper -Dmaven=3.3.9
answered Dec 20, 2016 at 10:01
Michal Kordas Michal Kordas
10.6k 8 8 gold badges 59 59 silver badges 106 106 bronze badges
The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don’t want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.
mvnw: it’s an executable Unix shell script used in place of a fully installed Maven
mvnw.cmd: it’s for Windows environment
Use Cases
The wrapper should work with different operating systems such as:
After that, we can run our goals like this for the Unix system:
./mvnw clean install
And the following command for Batch:
./mvnw.cmd clean install
If we don’t have the specified Maven in the wrapper properties, it’ll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists of the system.
Maven Wrapper plugin
Maven Wrapper plugin to make auto installation in a simple Spring Boot project.
First, we need to go in the main folder of the project and run this command:
mvn -N io.takari:maven:wrapper
We can also specify the version of Maven:
mvn -N io.takari:maven:wrapper -Dmaven=3.5.2
The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.
14.2k 5 5 gold badges 41 41 silver badges 70 70 bronze badges
answered Nov 13, 2019 at 15:26
Romil Patel Romil Patel
13.1k 8 8 gold badges 47 47 silver badges 77 77 bronze badges
Maybe you should mention that part of the text is extracted from baeldung.com/maven-wrapper
Sep 15, 2020 at 11:20
short answer: to run Maven and Gradle in the terminal without following manual installation processes.
./gradlew clean build ./gradlew bootRun
./mvnw clean install ./mvnw spring-boot:run
«The recommended way to execute any Gradle build is with the help of the Gradle Wrapper (in short just “Wrapper”). The Wrapper is a script that invokes a declared version of Gradle, downloading it beforehand if necessary. As a result, developers can get up and running with a Gradle project quickly without having to follow manual installation processes saving your company time and money.«
Gradle would also add some specific files corresponding to the Maven files Gradlew and Gradle.bat
A Quick Guide to Maven Wrapper

A quick guide to materially improve your tests with Junit 5:
Partner – Payara – NPI EA (cat=JAVA EE)
![]()
Accelerate Your Jakarta EE Development with Payara Server!
With best-in-class guides and documentation, Payara essentially simplifies deployment to diverse infrastructures.
Beyond that, it provides intelligent insights and actions to optimize Jakarta EE applications.
The goal is to apply an opinionated approach to get to what’s essential for mission-critical applications — really solid scalability, availability, security, and long-term support:
eBook – Persistence – NPI EA (cat=Persistence)
![]()
Working on getting your persistence layer right with Spring?
eBook – Jackson – NPI EA (cat=Jackson)
![]()
Do JSON right with Jackson
eBook – HTTP Client – NPI EA (cat=Http Client-Side)
![]()
Get the most out of the Apache HTTP Client
eBook – Maven – NPI EA (cat = Maven)
![]()
Get Started with Apache Maven:
Course – RwS – NPI EA (cat=REST)
![]()
Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Partner – Lightrun – NPI EA (cat=Spring)
![]()
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Course – LS – NPI EA (cat=Spring)
![]()
Get started with Spring and Spring Boot, through the reference Learn Spring course:
eBook – RwS – NPI EA (cat=Spring MVC)
![]()
Building a REST API with Spring?
Partner – Machinet – NPI EA (cat = Testing)
![]()
The AI Assistant to boost Boost your productivity writing unit tests — Machinet AI.
AI is all the rage these days, but for very good reason. The highly practical coding companion, you’ll get the power of AI-assisted coding and automated unit test generation.
Machinet’s Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.
And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.
Simplify Your Coding Journey with Machinet AI:
Partner – Codium – NPI EA (cat = Testing)
![]()
Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.
Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.
Write code that works the way you meant it to:
Partner – Bellsoft – NPI EA (cat = Spring/DevOps)
![]()
Looking for the ideal Linux distro for running modern Spring apps in the cloud?
Meet Alpaquita Linux: lightweight, secure, and powerful enough to handle heavy workloads.
This distro is specifically designed for running Java apps. It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.
Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:
Course – LSS – NPI EA (cat=Spring Security)
![]()
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses — Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Partner – Aegik AB – NPI EA (tag = SQL)
![]()
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Partner – DBSchema – NPI EA (tag = SQL)
![]()
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Course – LSD – NPI EA (tag=Spring Data JPA)
![]()
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course: