1. Introduction
1.介绍
Building a software project typically consists of such tasks as downloading dependencies, putting additional jars on a classpath, compiling source code into binary code, running tests, packaging compiled code into deployable artifacts such as JAR, WAR, and ZIP files, and deploying these artifacts to an application server or repository.
构建一个软件项目通常包括这样的任务:下载依赖关系,将额外的jars放在classpath上,将源代码编译成二进制代码,运行测试,将编译的代码打包成可部署的工件,如JAR、WAR和ZIP文件,并将这些工件部署到应用服务器或存储库。
Apache Maven automates these tasks, minimizing the risk of humans making errors while building the software manually and separating the work of compiling and packaging our code from that of code construction.
Apache Maven将这些工作自动化,最大限度地降低了人类在手动构建软件时出错的风险,并将我们的代码编译和打包工作与代码构建工作分开。
In this tutorial, we’re going to explore this powerful tool for describing, building, and managing Java software projects using a central piece of information — the Project Object Model (POM) — that is written in XML.
在本教程中,我们将探讨这个强大的工具,它使用一个中心信息–用XML编写的项目对象模型(POM),来描述、构建和管理Java软件项目。
2. Why Use Maven?
2.为什么要使用Maven?
The key features of Maven are:
Maven的主要特点是。
- simple project setup that follows best practices: Maven tries to avoid as much configuration as possible, by supplying project templates (named archetypes)
- dependency management: it includes automatic updating, downloading and validating the compatibility, as well as reporting the dependency closures (known also as transitive dependencies)
- isolation between project dependencies and plugins: with Maven, project dependencies are retrieved from the dependency repositories while any plugin’s dependencies are retrieved from the plugin repositories, resulting in fewer conflicts when plugins start to download additional dependencies
- central repository system: project dependencies can be loaded from the local file system or public repositories, such as Maven Central
3. Project Object Model
3.项目对象模型
The configuration of a Maven project is done via a Project Object Model (POM), represented by a pom.xml file. The POM describes the project, manages dependencies, and configures plugins for building the software.
Maven项目的配置是通过项目对象模型(POM)完成的,由pom.xml文件表示。POM描述了项目,管理了依赖关系,并配置了用于构建软件的插件。
The POM also defines the relationships among modules of multi-module projects. Let’s look at the basic structure of a typical POM file:
POM还定义了多模块项目的模块之间的关系。让我们看看一个典型的POM文件的基本结构。
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>baeldung</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>com.baeldung</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
//...
</plugin>
</plugins>
</build>
</project>
Let’s take a closer look at these constructs.
让我们仔细看一下这些结构。
3.1. Project Identifiers
3.1.项目标识符
Maven uses a set of identifiers, also called coordinates, to uniquely identify a project and specify how the project artifact should be packaged:
Maven使用一组标识符,也叫坐标,来唯一地识别一个项目,并指定项目工件的打包方式。
- groupId – a unique base name of the company or group that created the project
- artifactId – a unique name of the project
- version – a version of the project
- packaging – a packaging method (e.g. WAR/JAR/ZIP)
The first three of these (groupId:artifactId:version) combine to form the unique identifier and are the mechanism by which you specify which versions of external libraries (e.g. JARs) your project will use.
其中的前三个(groupId:artifactId:version)组合成唯一的标识符,是你指定项目将使用哪些版本的外部库(如JAR)的机制。
3.2. Dependencies
3.2.依赖性
These external libraries that a project uses are called dependencies. The dependency management feature in Maven ensures the automatic download of those libraries from a central repository, so you don’t have to store them locally.
项目使用的这些外部库被称为依赖项。Maven的依赖性管理功能可以确保从中央仓库自动下载这些库,因此你不必在本地存储这些库。
This is a key feature of Maven and provides the following benefits:
这是Maven的一项关键功能,具有以下好处。
- uses less storage by significantly reducing the number of downloads off remote repositories
- makes checking out a project quicker
- provides an effective platform for exchanging binary artifacts within your organization and beyond without the need for building artifacts from source every time
In order to declare a dependency on an external library, you need to provide the groupId, artifactId, and version of the library. Let’s take a look at an example:
为了声明对一个外部库的依赖,你需要提供该库的groupId、artifactId和version。让我们来看看一个例子。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.16</version>
</dependency>
As Maven processes the dependencies, it will download the Spring Core library into your local Maven repository.
当Maven处理依赖关系时,它会将Spring Core库下载到你的本地Maven资源库。
3.3. Repositories
3.3.存储库
A repository in Maven is used to hold build artifacts and dependencies of varying types. The default local repository is located in the .m2/repository folder under the home directory of the user.
Maven的资源库用于存放不同类型的构建工件和依赖。默认的本地资源库位于用户主目录下的.m2/repository文件夹中。
If an artifact or a plugin is available in the local repository, Maven uses it. Otherwise, it is downloaded from a central repository and stored in the local repository. The default central repository is Maven Central.
如果本地资源库中有工件或插件,Maven就会使用它。否则,它会从中央仓库下载并存储在本地仓库中。默认的中央仓库是Maven Central。
Some libraries, such as the JBoss server, are not available at the central repository but are available at an alternate repository. For those libraries, you need to provide the URL to the alternate repository inside the pom.xml file:
有些库,如JBoss服务器,在中央仓库中是不可用的,但在另一个仓库中可用。对于这些库,你需要在pom.xml文件中提供备用库的URL。
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
Please note that you can use multiple repositories in your projects.
请注意,你可以在你的项目中使用多个存储库。。
3.4. Properties
3.4.属性
Custom properties can help to make your pom.xml file easier to read and maintain. In the classic use case, you would use custom properties to define versions for your project’s dependencies.
自定义属性可以帮助使你的pom.xml文件更容易阅读和维护。在经典的使用案例中,你会使用自定义属性来为你的项目的依赖性定义版本。
Maven properties are value-placeholders and are accessible anywhere within a pom.xml by using the notation ${name}, where name is the property.
Maven属性是值占位符,可以在pom.xml中的任何地方使用${name},其中name是属性。
Let’s see an example:
让我们看一个例子。
<properties>
<spring.version>5.3.16</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
Now if you want to upgrade Spring to a newer version, you only have to change the value inside the<spring.version> property tag and all the dependencies using that property in their <version> tags will be updated.
现在,如果你想把Spring升级到一个较新的版本,你只需要改变<spring.version>属性标签内的值,所有在<version>标签中使用该属性的依赖关系都会被更新。
Properties are also often used to define build path variables:
属性也经常被用来定义构建路径变量。
<properties>
<project.build.folder>${project.build.directory}/tmp/</project.build.folder>
</properties>
<plugin>
//...
<outputDirectory>${project.resources.build.folder}</outputDirectory>
//...
</plugin>
3.5. Build
3.5.构建
The build section is also a very important section of the Maven POM. It provides information about the default Maven goal, the directory for the compiled project, and the final name of the application. The default build section looks like this:
build部分也是Maven POM中非常重要的部分。它提供了有关Maven默认目标、编译项目的目录和应用程序的最终名称的信息。默认的build部分看起来像这样。
<build>
<defaultGoal>install</defaultGoal>
<directory>${basedir}/target</directory>
<finalName>${artifactId}-${version}</finalName>
<filters>
<filter>filters/filter1.properties</filter>
</filters>
//...
</build>
The default output folder for compiled artifacts is named target, and the final name of the packaged artifact consists of the artifactId and version, but you can change it at any time.
编译工件的默认输出文件夹被命名为target,打包工件的最终名称由artifactId和version组成,但是你可以随时改变它。。
3.6. Using Profiles
3.6.使用Profiles
Another important feature of Maven is its support for profiles. A profile is basically a set of configuration values. By using profiles, you can customize the build for different environments such as Production/Test/Development:
Maven的另一个重要特点是支持profiles。profile基本上是一组配置值。通过使用profiles,你可以为不同环境(如生产/测试/开发)定制构建。
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
//...
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
//...
</plugin>
</plugins>
</build>
</profile>
</profiles>
As you can see in the example above, the default profile is set to development. If you want to run the production profile, you can use the following Maven command:
正如你在上面的例子中看到的,默认配置文件被设置为development。如果你想运行productionprofile,你可以使用以下Maven命令。
mvn clean install -Pproduction
4. Maven Build Lifecycles
4.Maven的构建生命周期
Every Maven build follows a specified lifecycle. You can execute several build lifecycle goals, including the ones to compile the project’s code, create a package, and install the archive file in the local Maven dependency repository.
每个Maven构建都遵循指定的生命周期。你可以执行多个构建生命周期目标,包括编译项目代码、创建包和安装本地Maven依赖库中的存档文件。
4.1. Lifecycle Phases
4.1.寿命周期阶段
The following list shows the most important Maven lifecycle phases:
以下列表显示了最重要的Maven生命周期阶段。
- validate – checks the correctness of the project
- compile – compiles the provided source code into binary artifacts
- test – executes unit tests
- package – packages compiled code into an archive file
- integration-test – executes additional tests, which require the packaging
- verify – checks if the package is valid
- install – installs the package file into the local Maven repository
- deploy – deploys the package file to a remote server or repository
4.2. Plugins and Goals
4.2. 插件和目标
A Maven plugin is a collection of one or more goals. Goals are executed in phases, which helps to determine the order in which the goals are executed.
一个Maven plugin是一个或多个goals的集合。目标是分阶段执行的,这有助于确定目标的执行顺序。
The rich list of plugins that are officially supported by Maven is available here. There is also an interesting article on how to build an executable JAR on Baeldung using various plugins.
Maven正式支持的丰富的插件列表可在这里找到。还有一篇有趣的文章,介绍了如何使用各种插件在Baeldung上构建可执行的JAR 。
To gain a better understanding of which goals are run in which phases by default, take a look at the default Maven lifecycle bindings.
为了更好地了解哪些目标默认在哪些阶段运行,请看默认的Maven 生命周期绑定。
To go through any one of the above phases, we just have to call one command:
要通过上述任何一个阶段,我们只需调用一个命令。
mvn <phase>
For example, mvn clean install will remove the previously created jar/war/zip files and compiled classes (clean) and execute all the phases necessary to install the new archive (install).
例如,mvn clean install将删除先前创建的jar/war/zip文件和编译的类(clean),并执行所有必要的阶段来安装新的存档(install)。
Please note that goals provided by plugins can be associated with different phases of the lifecycle.
请注意,由插件提供的目标可以与生命周期的不同阶段相关。
5. Your First Maven Project
5.你的第一个Maven项目
In this section, we will use the command line functionality of Maven to create a Java project.
本节中,我们将使用Maven的命令行功能来创建一个Java项目。
5.1. Generating a Simple Java Project
5.1.生成一个简单的Java项目
In order to build a simple Java project, let’s run the following command:
为了建立一个简单的Java项目,让我们运行以下命令。
mvn archetype:generate \
-DgroupId=com.baeldung \
-DartifactId=baeldung \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DarchetypeVersion=1.4 \
-DinteractiveMode=false
The groupId is a parameter indicating the group or individual that created a project, which is often a reversed company domain name. The artifactId is the base package name used in the project, and we use the standard archetype. Here we are using the latest archetype version to ensure our project is created with updated and latest structure.
groupId是一个参数,表示创建项目的团体或个人,这通常是一个反转的公司域名。artifactId是项目中使用的基础包名称,我们使用标准的archetype。在这里,我们使用最新的原型版本,以确保我们的项目是以更新和最新的结构创建的。
Since we didn’t specify the version and the packaging type, these will be set to default values — the version will be set to 1.0-SNAPSHOT, and the packaging will be jar by default.
由于我们没有指定版本和包装类型,这些将被设置为默认值–版本将被设置为1.0-SNAPSHOT,,包装将默认为jar。
If you don’t know which parameters to provide, you can always specify interactiveMode=true, so that Maven asks for all the required parameters.
如果您不知道要提供哪些参数,您可以随时指定interactiveMode=true,这样Maven就会询问所有需要的参数。
After the command completes, we have a Java project containing an App.java class, which is just a simple “Hello World” program, in the src/main/java folder.
命令完成后,我们在src/main/java文件夹下有一个包含App.java类的Java项目,这只是一个简单的 “Hello World “程序。
We also have an example test class in src/test/java. The pom.xml of this project will look similar to this:
我们在src/test/java中也有一个测试类的例子。这个项目的pom.xml将看起来与此类似。
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>baeldung</artifactId>
<version>1.0-SNAPSHOT</version>
<name>baeldung</name>
<url>http://www.example.com</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
As you can see, the JUnit dependency is provided by default.
正如你所看到的,JUnit的依赖性是默认提供的。
5.2. Compiling and Packaging a Project
5.2.编译和打包项目
The next step is to compile the project:
下一步是编译该项目。
mvn compile
Maven will run through all lifecycle phases needed by the compile phase to build the project’s sources. If you want to run only the test phase, you can use:
Maven将运行生命周期阶段所需的所有编译阶段,以构建项目的源代码。如果你只想运行test阶段,你可以使用。
mvn test
Now let’s invoke the package phase, which will produce the compiled archive jar file:
现在让我们调用package阶段,它将产生编译后的存档jar文件。
mvn package
5.3. Executing an Application
5.3.执行一个应用程序
Finally, we are going to execute our Java project with the exec-maven-plugin. Let’s configure the necessary plugins in the pom.xml:
最后,我们要用exec-maven-plugin来执行我们的Java项目。让我们在pom.xml中配置必要的插件。
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<mainClass>com.baeldung.java.App</mainClass>
</configuration>
</plugin>
</plugins>
</build>
The first plugin, maven-compiler-plugin, is responsible for compiling the source code using Java version 1.8. The exec-maven-plugin searches for the mainClass in our project.
第一个插件maven-compiler-plugin,负责使用Java 1.8版本编译源代码。exec-maven-plugin搜索我们项目中的mainClass。
To execute the application, we run the following command:
为了执行该应用程序,我们运行以下命令。
mvn exec:java
6. Conclusion
6.结论
In this article, we discussed some of the more popular features of the Apache Maven build tool.
在这篇文章中,我们讨论了Apache Maven构建工具的一些比较流行的功能。
All code examples on Baeldung are built using Maven, so you can easily check our GitHub project website to see various Maven configurations.
Baeldung上的所有代码示例都是使用Maven构建的,因此您可以轻松查看我们的GitHub项目网站,查看各种Maven配置。