Maven
一、Maven 简介
Maven 翻译为”专家”、”内行”,是 Apache下的一个纯 Java 开发的开源项目,主要用于 Java 项目,也支持 C#、Ruby、Scala 等语。Maven 的本质是一个项目管理工具,将项目开发和管理过程抽象成一个项目对象模型(POM)POM (Project Object Model):项目对象模型
Maven 功能
项目构建:提供标准的、跨平台的自动化项目构建方式
依赖管理:方便快捷的管理项目依赖的资源(jar包),避免资源间的版本冲突问题
统一开发结构:提供标准的、统一的项目结构
Maven 提倡使用一个共同的标准目录结构,Maven 使用约定优于配置的原则,大家尽可能的遵守这样的目录结构。如下所示:
| 目录 | 目的 |
|---|---|
| ${basedir} | 存放pom.xml和所有的子目录 |
| ${basedir}/src/main/java | 项目的java源代码 |
| ${basedir}/src/main/resources | 项目的资源,比如说property文件,springmvc.xml |
| ${basedir}/src/test/java | 项目的测试类,比如说Junit代码 |
| ${basedir}/src/test/resources | 测试用的资源 |
| ${basedir}/src/main/webapp/WEB-INF | web应用文件目录,web项目的信息,比如存放web.xml、本地图片、jsp视图页面 |
| ${basedir}/target | 打包输出目录 |
| ${basedir}/target/classes | 编译输出目录 |
| ${basedir}/target/test-classes | 测试编译输出目录 |
| Test.java | Maven只会自动运行符合该命名规则的测试类 |
| ~/.m2/repository | Maven默认的本地仓库目录位置 |
- 文档生成、报告、SCMs、发布、分发、邮件列表
二、Maven 基本概念
2.1 仓库
Maven 仓库是项目中依赖的第三方库,这个库所在的位置叫做仓库。在 Maven 中,任何一个依赖、插件或者项目构建的输出,都可以称之为构件。Maven 仓库能帮助我们管理构件(主要是 JAR),它就是放置所有 JAR 文件(WAR,ZIP,POM 等等)的地方。
Maven 仓库类型:
| 仓库类型 | 存储位置 | 作用 | 访问优先级 |
|---|---|---|---|
| 本地仓库 | 用户目录下的.m2/repository | 缓存远程下载的依赖 | 1 |
| 远程仓库 | 网络服务器 | 提供依赖和插件的集中存储 | 2 |
| - 中央仓库 | repo.maven.apache.org | Maven官方维护的默认仓库 | 2.1 |
| - 私服仓库 | 公司内部搭建(如Nexus) | 托管私有依赖,加速构建 | 2.2 |
| - 其他公共仓库 | 如阿里云、JCenter等 | 镜像或补充中央仓库 | 2.3 |
本地仓库
Maven 的本地仓库,在安装 Maven 后并不会创建,它是在第一次执行 maven 命令的时候才被创建。运行 Maven 的时候,Maven 所需要的任何构件都是直接从本地仓库获取的。如果本地仓库没有,它会首先尝试从远程仓库下载构件至本地仓库,然后再使用本地仓库的构件。默认情况下,不管 Linux 还是 Windows,每个用户在自己的用户目录下都有一个路径名为 .m2/repository/ 的仓库目录。
中央仓库
Maven 中央仓库是由 Maven 社区提供的仓库,其中包含了大量常用的库。中央仓库包含了绝大多数流行的开源 Java 构件,以及源码、作者信息、SCM、信息、许可证信息等。一般来说,简单的 Java 项目依赖的构件都可以在这里下载到。
远程仓库
如果 Maven 在中央仓库中也找不到依赖的文件,它会停止构建过程并输出错误信息到控制台。为避免这种情况,Maven 提供了远程仓库的概念,它是开发人员自己定制仓库,包含了所需要的代码库或者其他工程中用到的 jar 文件。
私服仓库
仓库类型:
| 仓库类型 | 用途 |
|---|---|
| hosted | 存放私有构件 |
| proxy | 代理远程仓库 |
| group | 聚合多个仓库 |
Maven 依赖搜索顺序
当我们执行 Maven 构建命令时,Maven 开始按照以下顺序查找依赖的库:
- 步骤 1 - 在本地仓库中搜索,如果找不到,执行步骤 2,如果找到了则执行其他操作。
- 步骤 2 - 在中央仓库中搜索,如果找不到,并且有一个或多个远程仓库已经设置,则执行步骤 4,如果找到了则下载到本地仓库中以备将来引用。
- 步骤 3 - 如果远程仓库没有被设置,Maven 将简单的停滞处理并抛出错误(无法找到依赖的文件)。
- 步骤 4 - 在一个或多个远程仓库中搜索依赖的文件,如果找到则下载到本地仓库以备将来引用,否则 Maven 将停止处理并抛出错误(无法找到依赖的文件)。
2.2 坐标
Maven中的坐标用于描述仓库中资源的位置
- Maven坐标主要组成
groupId: 定义当前Maven项目隶属组织名称 (通常是域名反写, 例如: org.mybatis)
artifactId: 定义当前Maven项目名称 (通常是模块名称, 例如CRM、SMS)
version: 定义当前项目版本号
packaging: 定义该项目的打包方式
2.3 POM
POM(Project Object Model,项目对象模型)是 Maven 项目的核心配置文件,通常命名为 pom.xml,放在项目根目录。Maven 会读取它来了解项目是什么、依赖哪些组件,以及如何构建和发布。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- POM 模型版本 -->
<modelVersion>4.0.0</modelVersion>
<!-- 项目组织标识 -->
<groupId>com.example</groupId>
<!-- 项目名称标识 -->
<artifactId>my-app</artifactId>
<!-- 项目版本 -->
<version>1.0.0</version>
<!-- 打包方式:jar、war 或 pom -->
<packaging>jar</packaging>
<!-- 项目名称和描述 -->
<name>My Application</name>
<description>A demo project</description>
<!-- 项目属性 -->
<properties>
<!-- Java 编译版本 -->
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<!-- 文件编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- 项目依赖 -->
<dependencies>
<!-- JUnit 测试依赖,仅测试时使用 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
所有 POM 文件都需要 project 元素和三个必需字段:groupId,artifactId,version。
POM 标签
以下是对 pom.xml 中所有重要标签的分类说明,涵盖 项目信息、依赖管理、构建配置、环境设置 等核心内容。
所有 POM 文件必须包含的标签: modelVersion、groupId、artifactId 和 version。
| 标签 | 类别 | 说明 | 示例/可选值 | 是否必需 |
|---|---|---|---|---|
| 基础信息 | ||||
<modelVersion> | 项目结构 | POM模型版本 | 4.0.0 | 是 |
<groupId> | 坐标 | 组织标识(反向域名) | com.example | 是 |
<artifactId> | 坐标 | 项目名称 | my-project | 是 |
<version> | 坐标 | 项目版本 | 1.0.0-SNAPSHOT | 是 |
<packaging> | 项目类型 | 打包格式 | jar/war/pom | 否(默认jar) |
<name> | 元信息 | 项目显示名称 | My Application | 否 |
<description> | 元信息 | 项目描述 | A demo project | 否 |
<url> | 元信息 | 项目主页URL | https://example.com | 否 |
| 依赖管理 | ||||
<dependencies> | 依赖 | 依赖列表容器 | 包含多个<dependency> | 否 |
<dependency> | 依赖 | 单个依赖定义 | 包含groupId等子标签 | 可选 |
<scope> | 依赖 | 依赖作用域 | compile/test/provided/runtime | 否(默认compile) |
<optional> | 依赖 | 是否可选依赖 | true/false | 否(默认false) |
<exclusions> | 依赖 | 排除传递性依赖 | 包含<exclusion>列表 | 否 |
| 构建配置 | ||||
<build> | 构建 | 构建配置容器 | 包含插件/资源等配置 | 否 |
<plugins> | 构建 | 插件列表容器 | 包含多个<plugin> | 否 |
<plugin> | 构建 | 单个插件定义 | 需指定groupId和artifactId | 可选 |
<resources> | 构建 | 资源文件配置 | 定义<resource>路径 | 否 |
<testResources> | 构建 | 测试资源文件配置 | 类似<resources> | 否 |
<finalName> | 构建 | 最终打包文件名 | my-app | 否 |
| 环境配置 | ||||
<properties> | 配置 | 自定义变量容器 | 定义键值对 | 否 |
<java.version> | 属性 | Java版本变量 | 11/17等 | 否 |
<repositories> | 仓库 | 自定义远程仓库列表 | 包含<repository> | 否 |
<pluginRepositories> | 仓库 | 自定义插件仓库 | 类似<repositories> | 否 |
| 多模块管理 | ||||
<modules> | 模块 | 子模块列表 | 包含多个<module> | 聚合项目需要 |
<parent> | 继承 | 父POM引用 | 需指定父项目坐标 | 继承项目需要 |
<dependencyManagement> | 依赖 | 统一管理依赖版本 | 定义版本但不引入 | 否 |
<profiles> | 配置 | 环境profile容器 | 定义不同环境配置 | 否 |
| 其他信息 | ||||
<licenses> | 法律 | 许可证信息 | 包含<license> | 否 |
<developers> | 人员 | 开发者列表 | 包含<developer> | 否 |
<contributors> | 人员 | 贡献者列表 | 类似<developers> | 否 |
<issueManagement> | 管理 | 问题跟踪系统 | 定义issue系统URL | 否 |
2.4 生命周期
Maven 生命周期定义了项目从清理、构建到发布的步骤。Maven 有三条相互独立的标准生命周期:clean、default 和 site。每条生命周期由多个阶段(phase)组成,按顺序执行。
2.4.1 Clean 生命周期:清理项目
| 阶段 | 作用 |
|---|---|
pre-clean | 清理前的准备工作 |
clean | 删除上一次构建生成的文件,通常是 target/ 目录 |
post-clean | 清理后的收尾工作 |
执行一个阶段时,会先执行同一生命周期中排在它前面的阶段。例如,mvn clean 会依次执行 pre-clean 和 clean。
2.4.2 Default 生命周期:构建项目
这是 Maven 最常用的生命周期,主要阶段如下:
| 阶段 | 作用 |
|---|---|
validate | 检查项目是否正确,构建所需信息是否完整 |
compile | 编译主代码 |
test | 运行单元测试 |
package | 将代码打包成 JAR、WAR 等文件 |
verify | 检查打包结果是否符合要求 |
install | 将构建结果安装到本地 Maven 仓库 |
deploy | 将构建结果发布到远程仓库 |
调用某个阶段时,Maven 会按顺序执行它之前的阶段。mvn test,会先完成测试所需的前置步骤,包括编译主代码、编译测试代码,然后运行测试。
常用命令:
1
2
3
4
5
mvn compile # 编译主代码
mvn test # 运行测试
mvn package # 打包
mvn install # 安装到本地仓库
mvn deploy # 发布到远程仓库
2.4.3 Site 生命周期:生成项目文档
| 阶段 | 作用 |
|---|---|
pre-site | 生成站点前的准备工作 |
site | 生成项目站点文档 |
post-site | 生成站点后的收尾工作 |
site-deploy | 发布项目站点文档 |
通常开发中最常用的是 clean 和 default 生命周期;site 常用于生成项目文档。
2.5 插件
Maven 插件是扩展 Maven 功能的组件,具体执行编译、测试、打包、部署等任务。一个插件可以包含多个目标(goal)。可以把它记成:生命周期规定步骤,插件目标完成具体工作。
编译与资源处理
| 插件 | 主要作用 | 常见目标 |
|---|---|---|
maven-compiler-plugin | 编译 Java 主代码和测试代码,可设置 Java 版本、编码等 | compile、testCompile |
maven-resources-plugin | 复制资源文件,并可替换资源文件中的属性变量 | resources、testResources |
测试
| 插件 | 主要作用 | 常见目标 |
|---|---|---|
maven-surefire-plugin | 运行单元测试,通常用于 mvn test 阶段 | test |
maven-failsafe-plugin | 运行集成测试,通常用于 integration-test 和 verify 阶段 | integration-test、verify |
一般来说,Surefire 用于单元测试,Failsafe 用于集成测试。集成测试往往需要启动服务或准备外部环境,Failsafe 通常会把测试执行和结果检查分开。
打包
| 插件 | 主要作用 | 常见目标 |
|---|---|---|
maven-jar-plugin | 将项目打包为 JAR 文件,可设置 JAR 清单信息 | jar |
maven-war-plugin | 将 Web 项目打包为 WAR 文件 | war |
maven-assembly-plugin | 按指定规则组合文件、依赖和目录,生成自定义分发包 | single |
maven-shade-plugin | 将项目及依赖打进一个 JAR,也可处理依赖冲突 | shade |
maven-jar-plugin 生成的普通 JAR 通常不包含所有运行时依赖。若想把依赖也打入一个 JAR,可以考虑 Shade 插件。
清理、安装与发布
| 插件 | 主要作用 | 常见目标 |
|---|---|---|
maven-clean-plugin | 删除构建输出目录,通常是 target/ | clean |
maven-install-plugin | 将构建产物安装到本地 Maven 仓库,供本机其他项目引用 | install |
maven-deploy-plugin | 将构建产物发布到远程 Maven 仓库 | deploy |
依赖管理与项目检查
| 插件 | 主要作用 | 常见目标示例 |
|---|---|---|
maven-dependency-plugin | 查看、分析或复制项目依赖 | dependency:tree、dependency:copy-dependencies |
maven-enforcer-plugin | 检查并强制执行项目规则,例如 Maven 或 JDK 版本要求 | enforcer:enforce |
maven-checkstyle-plugin | 根据 Checkstyle 规则检查 Java 代码风格 | checkstyle:check |
maven-surefire-report-plugin | 根据单元测试结果生成报告 | surefire-report:report |
这类插件常被直接调用,不一定是常规构建阶段的一部分。例如,查看依赖树:
1
mvn dependency:tree
文档与项目模板
| 插件 | 主要作用 | 常见目标示例 |
|---|---|---|
maven-site-plugin | 生成 Maven 项目站点和文档 | site:site |
maven-javadoc-plugin | 生成 Java API 文档 | javadoc:javadoc |
maven-archetype-plugin | 根据项目模板创建项目骨架 | archetype:generate |
三、Maven 常用命令
基础与构建命令
| 命令 | 作用 |
|---|---|
mvn -v | 查看 Maven 版本、Java 版本等环境信息 |
mvn clean | 清理构建生成的文件,通常删除 target/ 目录 |
mvn validate | 检查项目是否正确,构建所需信息是否完整 |
mvn compile | 编译项目主代码,生成的 class 文件通常在 target/classes/ |
mvn test-compile | 编译测试代码 |
mvn test | 运行项目中的单元测试 |
mvn package | 执行前置构建步骤,并按 POM 配置打包成 JAR、WAR 等 |
mvn verify | 执行检查,验证构建结果是否符合要求 |
mvn install | 构建项目并将产物安装到本地 Maven 仓库 |
mvn deploy | 构建项目并将产物发布到远程仓库 |
依赖管理命令
| 命令 | 作用 |
|---|---|
mvn dependency:resolve | 解析项目依赖,下载本地尚未缓存的依赖 |
mvn dependency:tree | 显示项目依赖树,便于查看依赖关系和排查冲突 |
mvn dependency:analyze | 分析已声明但未使用、或使用但未声明的依赖 |
mvn dependency:sources | 下载项目依赖的源代码 |
mvn dependency:copy-dependencies | 将项目依赖复制到指定目录 |
mvn dependency:purge-local-repository | 清理本地仓库中当前项目使用的依赖缓存 |
项目创建命令
| 命令 | 作用 |
|---|---|
mvn archetype:generate | 根据 Maven 原型模板交互式创建项目 |
mvn archetype:generate -DgroupId=com.example -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false | 根据 Quickstart 模板创建基础 Java 项目 |
mvn archetype:generate -DgroupId=com.example -DartifactId=my-web-app -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false | 根据 Webapp 模板创建 Web 项目 |
测试命令
| 命令 | 作用 |
|---|---|
mvn test | 运行所有测试 |
mvn test -Dtest=TestClassName | 只运行指定测试类 |
mvn test -Dtest=TestClassName#testMethodName | 只运行指定测试类中的方法 |
mvn package -DskipTests | 打包时跳过运行测试,但仍会编译测试代码 |
mvn package -Dmaven.test.skip=true | 打包时跳过测试代码的编译和运行 |
插件与项目信息命令
| 命令 | 作用 |
|---|---|
mvn help:effective-pom | 查看继承、属性等配置合并后的最终 POM |
mvn help:describe -Dplugin=compiler | 查看指定插件的信息 |
mvn help:describe -Dcmd=compile | 查看 compile 命令对应的说明 |
mvn compiler:compile | 直接调用编译插件的 compile 目标 |
mvn site | 生成项目站点文档和报告 |
多模块项目命令
| 命令 | 作用 |
|---|---|
mvn -pl 模块名 compile | 只对指定模块执行命令 |
mvn -am -pl 模块名 compile | 构建指定模块以及它依赖的其他模块 |
mvn -rf 模块名 package | 从指定模块继续构建,常用于失败后重试 |
常用选项
| 选项 | 作用 |
|---|---|
-DskipTests | 跳过运行测试,但仍编译测试代码 |
-U | 强制检查远程仓库中的更新,常用于刷新 SNAPSHOT 依赖 |
-o | 离线模式,只使用本地已有的依赖和插件 |
-X | 输出详细调试信息,帮助排查构建问题 |
-P profile名 | 启用指定的 Maven Profile |
-T 4 | 使用 4 个线程并行构建 |
四、一个 Maven 项目
1
2
3
4
5
6
7
8
9
10
java-project/ Java 项目目录
├── pom.xml Maven 项目配置文件:定义项目依赖、构建方式和插件等
└── src/ 源代码和资源目录
├── main/ 正式程序内容
│ ├── java/ Java 源代码
│ └── resources/ 程序运行所需的配置、图片等资源
└── test/ 测试相关内容
├── java/ 测试代码
└── resources/ 测试使用的配置和样例数据
1. Introduction to Maven
Maven means “expert” or “connoisseur.” It is an open-source Apache project written in Java, primarily used for Java projects, with support for other languages such as C#, Ruby, and Scala. Maven is a project management tool that represents project development and management through a Project Object Model (POM).
Maven features
- Project building: provides a standard, cross-platform approach to automated builds.
- Dependency management: manages project dependencies, such as JAR files, and helps resolve version conflicts.
- Standard project structure: provides a consistent directory layout.
Maven follows the convention-over-configuration principle and encourages the following standard directory structure:
| Directory | Purpose |
|---|---|
${basedir} | Contains pom.xml and all project subdirectories |
${basedir}/src/main/java | Application Java source code |
${basedir}/src/main/resources | Application resources, such as properties files and springmvc.xml |
${basedir}/src/test/java | Test source code, such as JUnit tests |
${basedir}/src/test/resources | Test resources |
${basedir}/src/main/webapp/WEB-INF | Web application configuration and protected resources |
${basedir}/target | Build output directory |
${basedir}/target/classes | Compiled application classes |
${basedir}/target/test-classes | Compiled test classes |
Test.java | Test classes are automatically selected according to test naming conventions |
~/.m2/repository | Default local Maven repository |
- Other features include documentation, reports, source control integration, releases, distribution, and mailing list information.
2. Core Maven Concepts
2.1 Repositories
A Maven repository stores artifacts used by projects. Dependencies, plugins, and project build outputs are all artifacts. Repositories manage JAR files as well as WAR, ZIP, POM, and other artifact types.
Types of Maven repositories
| Repository type | Location | Purpose | Lookup priority |
|---|---|---|---|
| Local repository | .m2/repository in the user’s home directory | Caches dependencies downloaded from remote repositories | 1 |
| Remote repository | Network server | Central storage for dependencies and plugins | 2 |
| Central repository | repo.maven.apache.org | Default repository maintained by the Maven community | 2.1 |
| Private repository | Internal server, such as Nexus | Hosts private artifacts and speeds up builds | 2.2 |
| Other public repositories | Mirrors or additional public repositories | Mirror or supplement Maven Central | 2.3 |
Local repository
The local repository is created when Maven first needs it, rather than during installation. Maven uses locally available artifacts; if an artifact is missing, it attempts to download it from a remote repository and cache it locally. By default, the repository is located at .m2/repository/ in the user’s home directory on both Linux and Windows.
Central repository
Maven Central is provided by the Maven community and contains many commonly used libraries. It hosts popular open-source Java artifacts, source code, author details, source control information, and license information. Dependencies for simple Java projects are usually available there.
Remote repositories
If Maven cannot find a required artifact, the build fails with an error. Developers can configure additional remote repositories containing libraries or JAR files produced by other projects.
Private repositories
| Repository type | Purpose |
|---|---|
hosted | Stores private artifacts |
proxy | Proxies a remote repository |
group | Aggregates multiple repositories |
Dependency lookup
The dependency lookup process can be summarized as follows:
- Search the local repository. If the artifact is available, use it.
- Search Maven Central and download a matching artifact into the local repository.
- If the artifact is missing and no additional remote repositories are configured, fail the build.
- Search configured remote repositories. Download a matching artifact into the local repository, or fail if it cannot be found.
2.2 Coordinates
Maven coordinates identify an artifact in a repository.
groupId: identifies the organization, usually using a reversed domain name, such asorg.mybatis.artifactId: identifies the project or module, such as CRM or SMS.version: identifies the project version.packaging: specifies the packaging type.
2.3 POM
The Project Object Model (POM) is the central configuration for a Maven project. It is normally stored in pom.xml at the project root. Maven reads it to determine the project’s identity, dependencies, build configuration, and publication settings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- POM model version -->
<modelVersion>4.0.0</modelVersion>
<!-- Organization identifier -->
<groupId>com.example</groupId>
<!-- Project identifier -->
<artifactId>my-app</artifactId>
<!-- Project version -->
<version>1.0.0</version>
<!-- Packaging type: jar, war, or pom -->
<packaging>jar</packaging>
<!-- Project name and description -->
<name>My Application</name>
<description>A demo project</description>
<!-- Project properties -->
<properties>
<!-- Java compilation version -->
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<!-- File encoding -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- Project dependencies -->
<dependencies>
<!-- JUnit is used only for testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
A POM uses a project root element and identifies the project through groupId, artifactId, and version.
POM elements
The following table groups important pom.xml elements by project information, dependency management, build configuration, and environment settings. A POM specifies modelVersion, groupId, artifactId, and version.
| Element | Category | Description | Example / values | Required |
|---|---|---|---|---|
| Basic information | ||||
<modelVersion> | Structure | POM model version | 4.0.0 | Yes |
<groupId> | Coordinates | Organization identifier | com.example | Yes |
<artifactId> | Coordinates | Project identifier | my-project | Yes |
<version> | Coordinates | Project version | 1.0.0-SNAPSHOT | Yes |
<packaging> | Project type | Packaging format | jar / war / pom | No; defaults to jar |
<name> | Metadata | Display name | My Application | No |
<description> | Metadata | Project description | A demo project | No |
<url> | Metadata | Project website | https://example.com | No |
| Dependency management | ||||
<dependencies> | Dependencies | Dependency list | Contains <dependency> elements | No |
<dependency> | Dependencies | A dependency declaration | Contains coordinates and other settings | Optional |
<scope> | Dependencies | Dependency scope | compile / test / provided / runtime | No; defaults to compile |
<optional> | Dependencies | Whether a dependency is optional | true / false | No; defaults to false |
<exclusions> | Dependencies | Excludes transitive dependencies | Contains <exclusion> elements | No |
| Build configuration | ||||
<build> | Build | Build settings | Plugins, resources, and other settings | No |
<plugins> | Build | Plugin list | Contains <plugin> elements | No |
<plugin> | Build | A plugin declaration | Identified by groupId and artifactId | Optional |
<resources> | Build | Application resource settings | Defines <resource> paths | No |
<testResources> | Build | Test resource settings | Similar to <resources> | No |
<finalName> | Build | Final output filename | my-app | No |
| Environment configuration | ||||
<properties> | Configuration | Custom properties | Key-value pairs | No |
<java.version> | Properties | A Java version property | 11 / 17 | No |
<repositories> | Repositories | Additional remote repositories | Contains <repository> elements | No |
<pluginRepositories> | Repositories | Plugin repositories | Similar to <repositories> | No |
| Multi-module management | ||||
<modules> | Modules | Child module list | Contains <module> elements | Required for aggregation |
<parent> | Inheritance | Parent POM reference | Specifies parent coordinates | Required for inheritance |
<dependencyManagement> | Dependencies | Central dependency configuration | Defines versions without adding dependencies | No |
<profiles> | Configuration | Environment-specific profiles | Defines alternative configurations | No |
| Other information | ||||
<licenses> | Legal | License information | Contains <license> elements | No |
<developers> | People | Developer list | Contains <developer> elements | No |
<contributors> | People | Contributor list | Similar to <developers> | No |
<issueManagement> | Management | Issue tracker settings | Issue tracker URL and system | No |
2.4 Lifecycles
Maven lifecycles define the steps for cleaning, building, and publishing a project. Maven has three independent standard lifecycles: clean, default, and site. Each consists of phases executed in order.
2.4.1 Clean Lifecycle: Cleaning the Project
| Phase | Purpose |
|---|---|
pre-clean | Preparation before cleaning |
clean | Deletes previous build output, usually target/ |
post-clean | Tasks after cleaning |
Invoking a phase also executes earlier phases in the same lifecycle. For example, mvn clean runs pre-clean followed by clean.
2.4.2 Default Lifecycle: Building the Project
This is the most frequently used lifecycle. Its main phases include:
| Phase | Purpose |
|---|---|
validate | Checks that the project and required build information are valid |
compile | Compiles application code |
test | Runs unit tests |
package | Packages the code into a JAR, WAR, or another format |
verify | Checks that the package meets requirements |
install | Installs build artifacts into the local Maven repository |
deploy | Publishes build artifacts to a remote repository |
Invoking a phase runs all earlier phases in order. For example, mvn test compiles application code and test code before running tests.
Common commands:
1
2
3
4
5
mvn compile # Compile application code
mvn test # Run tests
mvn package # Package the project
mvn install # Install into the local repository
mvn deploy # Publish to a remote repository
2.4.3 Site Lifecycle: Generating Project Documentation
| Phase | Purpose |
|---|---|
pre-site | Preparation before generating the site |
site | Generates project site documentation |
post-site | Tasks after generating the site |
site-deploy | Publishes the project site |
The clean and default lifecycles are most common during development. The site lifecycle is used for project documentation.
2.5 Plugins
Maven plugins perform tasks such as compilation, testing, packaging, and deployment. Each plugin can contain several goals. Lifecycles define the sequence of steps; plugin goals perform the work.
Compilation and resource processing
| Plugin | Purpose | Common goals |
|---|---|---|
maven-compiler-plugin | Compiles application and test code; configures Java versions and encoding | compile, testCompile |
maven-resources-plugin | Copies resources and optionally replaces property placeholders | resources, testResources |
Testing
| Plugin | Purpose | Common goals |
|---|---|---|
maven-surefire-plugin | Runs unit tests, usually during the test phase | test |
maven-failsafe-plugin | Runs integration tests during integration-test and checks results during verify | integration-test, verify |
Surefire is used for unit tests; Failsafe is used for integration tests. Integration tests may require running services or external environments. Failsafe separates test execution from checking the results.
Packaging
| Plugin | Purpose | Common goals |
|---|---|---|
maven-jar-plugin | Packages JAR files and configures manifest information | jar |
maven-war-plugin | Packages web applications into WAR files | war |
maven-assembly-plugin | Combines files, dependencies, and directories into distribution archives | single |
maven-shade-plugin | Bundles a project and its dependencies into a JAR and can handle dependency conflicts | shade |
A regular JAR produced by maven-jar-plugin usually does not include all runtime dependencies. Shade can bundle dependencies into the JAR.
Cleaning, installation, and publication
| Plugin | Purpose | Common goals |
|---|---|---|
maven-clean-plugin | Deletes build output, usually target/ | clean |
maven-install-plugin | Installs artifacts into the local repository for other local projects to use | install |
maven-deploy-plugin | Publishes artifacts to a remote Maven repository | deploy |
Dependency management and project checks
| Plugin | Purpose | Example goals |
|---|---|---|
maven-dependency-plugin | Displays, analyzes, or copies dependencies | dependency:tree, dependency:copy-dependencies |
maven-enforcer-plugin | Enforces project rules, such as Maven and JDK version requirements | enforcer:enforce |
maven-checkstyle-plugin | Checks Java code against Checkstyle rules | checkstyle:check |
maven-surefire-report-plugin | Generates reports from unit test results | surefire-report:report |
These goals are often invoked directly and may not be part of a regular build. For example, display the dependency tree with:
1
mvn dependency:tree
Documentation and project templates
| Plugin | Purpose | Example goals |
|---|---|---|
maven-site-plugin | Generates a Maven project site and documentation | site:site |
maven-javadoc-plugin | Generates Java API documentation | javadoc:javadoc |
maven-archetype-plugin | Creates a project skeleton from a template | archetype:generate |
3. Common Maven Commands
Basic build commands
| Command | Purpose |
|---|---|
mvn -v | Displays Maven, Java, and environment information |
mvn clean | Deletes build output, usually target/ |
mvn validate | Validates the project and required build information |
mvn compile | Compiles application code, usually into target/classes/ |
mvn test-compile | Compiles test code |
mvn test | Runs unit tests |
mvn package | Runs preceding build phases and packages according to the POM |
mvn verify | Runs checks on the build result |
mvn install | Builds and installs artifacts into the local repository |
mvn deploy | Builds and publishes artifacts to a remote repository |
Dependency management commands
| Command | Purpose |
|---|---|
mvn dependency:resolve | Resolves dependencies and downloads those missing locally |
mvn dependency:tree | Displays dependency relationships and helps diagnose conflicts |
mvn dependency:analyze | Analyzes unused declared dependencies and used undeclared dependencies |
mvn dependency:sources | Downloads dependency source code |
mvn dependency:copy-dependencies | Copies dependencies to a chosen directory |
mvn dependency:purge-local-repository | Clears cached dependencies used by the current project |
Project creation commands
| Command | Purpose |
|---|---|
mvn archetype:generate | Interactively creates a project from an archetype |
mvn archetype:generate -DgroupId=com.example -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false | Creates a basic Java project using Quickstart |
mvn archetype:generate -DgroupId=com.example -DartifactId=my-web-app -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false | Creates a web project using Webapp |
Testing commands
| Command | Purpose |
|---|---|
mvn test | Runs all tests |
mvn test -Dtest=TestClassName | Runs a specified test class |
mvn test -Dtest=TestClassName#testMethodName | Runs a specified test method |
mvn package -DskipTests | Packages without running tests; still compiles test code |
mvn package -Dmaven.test.skip=true | Packages without compiling or running tests |
Plugin and project information commands
| Command | Purpose |
|---|---|
mvn help:effective-pom | Displays the final POM after inheritance and configuration merging |
mvn help:describe -Dplugin=compiler | Describes a plugin |
mvn help:describe -Dcmd=compile | Describes the compile phase |
mvn compiler:compile | Directly invokes the compiler plugin’s compile goal |
mvn site | Generates project site documentation and reports |
Multi-module commands
| Command | Purpose |
|---|---|
mvn -pl 模块名 compile | Runs a command for selected modules; replace 模块名 with the module name |
mvn -am -pl 模块名 compile | Builds selected modules and their required modules |
mvn -rf 模块名 package | Resumes the build from a specified module after a failure |
Common options
| Option | Purpose |
|---|---|
-DskipTests | Skips test execution but still compiles test code |
-U | Forces remote update checks, often used for SNAPSHOT dependencies |
-o | Uses only locally available dependencies and plugins in offline mode |
-X | Prints detailed debugging information |
-P profile名 | Activates the specified profile; replace profile名 with its name |
-T 4 | Uses four threads for parallel builds |
4. A Maven Project
1
2
3
4
5
6
7
8
9
java-project/ Java project directory
├── pom.xml Maven configuration: dependencies, build settings, and plugins
└── src/ Source code and resources
├── main/ Application content
│ ├── java/ Java source code
│ └── resources/ Configuration, images, and other runtime resources
└── test/ Test content
├── java/ Test source code
└── resources/ Test configuration and sample data