Maven

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-INFweb应用文件目录,web项目的信息,比如存放web.xml、本地图片、jsp视图页面
${basedir}/target打包输出目录
${basedir}/target/classes编译输出目录
${basedir}/target/test-classes测试编译输出目录
Test.javaMaven只会自动运行符合该命名规则的测试类
~/.m2/repositoryMaven默认的本地仓库目录位置
  • 文档生成、报告、SCMs、发布、分发、邮件列表

二、Maven 基本概念

2.1 仓库

Maven 仓库是项目中依赖的第三方库,这个库所在的位置叫做仓库。在 Maven 中,任何一个依赖、插件或者项目构建的输出,都可以称之为构件。Maven 仓库能帮助我们管理构件(主要是 JAR),它就是放置所有 JAR 文件(WAR,ZIP,POM 等等)的地方。

Maven 仓库类型:

仓库类型存储位置作用访问优先级
本地仓库用户目录下的.m2/repository缓存远程下载的依赖1
远程仓库网络服务器提供依赖和插件的集中存储2
- 中央仓库repo.maven.apache.orgMaven官方维护的默认仓库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>元信息项目主页URLhttps://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:

DirectoryPurpose
${basedir}Contains pom.xml and all project subdirectories
${basedir}/src/main/javaApplication Java source code
${basedir}/src/main/resourcesApplication resources, such as properties files and springmvc.xml
${basedir}/src/test/javaTest source code, such as JUnit tests
${basedir}/src/test/resourcesTest resources
${basedir}/src/main/webapp/WEB-INFWeb application configuration and protected resources
${basedir}/targetBuild output directory
${basedir}/target/classesCompiled application classes
${basedir}/target/test-classesCompiled test classes
Test.javaTest classes are automatically selected according to test naming conventions
~/.m2/repositoryDefault 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 typeLocationPurposeLookup priority
Local repository.m2/repository in the user’s home directoryCaches dependencies downloaded from remote repositories1
Remote repositoryNetwork serverCentral storage for dependencies and plugins2
Central repositoryrepo.maven.apache.orgDefault repository maintained by the Maven community2.1
Private repositoryInternal server, such as NexusHosts private artifacts and speeds up builds2.2
Other public repositoriesMirrors or additional public repositoriesMirror or supplement Maven Central2.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 typePurpose
hostedStores private artifacts
proxyProxies a remote repository
groupAggregates multiple repositories

Dependency lookup

The dependency lookup process can be summarized as follows:

  1. Search the local repository. If the artifact is available, use it.
  2. Search Maven Central and download a matching artifact into the local repository.
  3. If the artifact is missing and no additional remote repositories are configured, fail the build.
  4. 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 as org.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.

ElementCategoryDescriptionExample / valuesRequired
Basic information    
<modelVersion>StructurePOM model version4.0.0Yes
<groupId>CoordinatesOrganization identifiercom.exampleYes
<artifactId>CoordinatesProject identifiermy-projectYes
<version>CoordinatesProject version1.0.0-SNAPSHOTYes
<packaging>Project typePackaging formatjar / war / pomNo; defaults to jar
<name>MetadataDisplay nameMy ApplicationNo
<description>MetadataProject descriptionA demo projectNo
<url>MetadataProject websitehttps://example.comNo
Dependency management    
<dependencies>DependenciesDependency listContains <dependency> elementsNo
<dependency>DependenciesA dependency declarationContains coordinates and other settingsOptional
<scope>DependenciesDependency scopecompile / test / provided / runtimeNo; defaults to compile
<optional>DependenciesWhether a dependency is optionaltrue / falseNo; defaults to false
<exclusions>DependenciesExcludes transitive dependenciesContains <exclusion> elementsNo
Build configuration    
<build>BuildBuild settingsPlugins, resources, and other settingsNo
<plugins>BuildPlugin listContains <plugin> elementsNo
<plugin>BuildA plugin declarationIdentified by groupId and artifactIdOptional
<resources>BuildApplication resource settingsDefines <resource> pathsNo
<testResources>BuildTest resource settingsSimilar to <resources>No
<finalName>BuildFinal output filenamemy-appNo
Environment configuration    
<properties>ConfigurationCustom propertiesKey-value pairsNo
<java.version>PropertiesA Java version property11 / 17No
<repositories>RepositoriesAdditional remote repositoriesContains <repository> elementsNo
<pluginRepositories>RepositoriesPlugin repositoriesSimilar to <repositories>No
Multi-module management    
<modules>ModulesChild module listContains <module> elementsRequired for aggregation
<parent>InheritanceParent POM referenceSpecifies parent coordinatesRequired for inheritance
<dependencyManagement>DependenciesCentral dependency configurationDefines versions without adding dependenciesNo
<profiles>ConfigurationEnvironment-specific profilesDefines alternative configurationsNo
Other information    
<licenses>LegalLicense informationContains <license> elementsNo
<developers>PeopleDeveloper listContains <developer> elementsNo
<contributors>PeopleContributor listSimilar to <developers>No
<issueManagement>ManagementIssue tracker settingsIssue tracker URL and systemNo

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

PhasePurpose
pre-cleanPreparation before cleaning
cleanDeletes previous build output, usually target/
post-cleanTasks 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:

PhasePurpose
validateChecks that the project and required build information are valid
compileCompiles application code
testRuns unit tests
packagePackages the code into a JAR, WAR, or another format
verifyChecks that the package meets requirements
installInstalls build artifacts into the local Maven repository
deployPublishes 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

PhasePurpose
pre-sitePreparation before generating the site
siteGenerates project site documentation
post-siteTasks after generating the site
site-deployPublishes 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

PluginPurposeCommon goals
maven-compiler-pluginCompiles application and test code; configures Java versions and encodingcompile, testCompile
maven-resources-pluginCopies resources and optionally replaces property placeholdersresources, testResources

Testing

PluginPurposeCommon goals
maven-surefire-pluginRuns unit tests, usually during the test phasetest
maven-failsafe-pluginRuns integration tests during integration-test and checks results during verifyintegration-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

PluginPurposeCommon goals
maven-jar-pluginPackages JAR files and configures manifest informationjar
maven-war-pluginPackages web applications into WAR fileswar
maven-assembly-pluginCombines files, dependencies, and directories into distribution archivessingle
maven-shade-pluginBundles a project and its dependencies into a JAR and can handle dependency conflictsshade

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

PluginPurposeCommon goals
maven-clean-pluginDeletes build output, usually target/clean
maven-install-pluginInstalls artifacts into the local repository for other local projects to useinstall
maven-deploy-pluginPublishes artifacts to a remote Maven repositorydeploy

Dependency management and project checks

PluginPurposeExample goals
maven-dependency-pluginDisplays, analyzes, or copies dependenciesdependency:tree, dependency:copy-dependencies
maven-enforcer-pluginEnforces project rules, such as Maven and JDK version requirementsenforcer:enforce
maven-checkstyle-pluginChecks Java code against Checkstyle rulescheckstyle:check
maven-surefire-report-pluginGenerates reports from unit test resultssurefire-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

PluginPurposeExample goals
maven-site-pluginGenerates a Maven project site and documentationsite:site
maven-javadoc-pluginGenerates Java API documentationjavadoc:javadoc
maven-archetype-pluginCreates a project skeleton from a templatearchetype:generate

3. Common Maven Commands

Basic build commands

CommandPurpose
mvn -vDisplays Maven, Java, and environment information
mvn cleanDeletes build output, usually target/
mvn validateValidates the project and required build information
mvn compileCompiles application code, usually into target/classes/
mvn test-compileCompiles test code
mvn testRuns unit tests
mvn packageRuns preceding build phases and packages according to the POM
mvn verifyRuns checks on the build result
mvn installBuilds and installs artifacts into the local repository
mvn deployBuilds and publishes artifacts to a remote repository

Dependency management commands

CommandPurpose
mvn dependency:resolveResolves dependencies and downloads those missing locally
mvn dependency:treeDisplays dependency relationships and helps diagnose conflicts
mvn dependency:analyzeAnalyzes unused declared dependencies and used undeclared dependencies
mvn dependency:sourcesDownloads dependency source code
mvn dependency:copy-dependenciesCopies dependencies to a chosen directory
mvn dependency:purge-local-repositoryClears cached dependencies used by the current project

Project creation commands

CommandPurpose
mvn archetype:generateInteractively creates a project from an archetype
mvn archetype:generate -DgroupId=com.example -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=falseCreates a basic Java project using Quickstart
mvn archetype:generate -DgroupId=com.example -DartifactId=my-web-app -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=falseCreates a web project using Webapp

Testing commands

CommandPurpose
mvn testRuns all tests
mvn test -Dtest=TestClassNameRuns a specified test class
mvn test -Dtest=TestClassName#testMethodNameRuns a specified test method
mvn package -DskipTestsPackages without running tests; still compiles test code
mvn package -Dmaven.test.skip=truePackages without compiling or running tests

Plugin and project information commands

CommandPurpose
mvn help:effective-pomDisplays the final POM after inheritance and configuration merging
mvn help:describe -Dplugin=compilerDescribes a plugin
mvn help:describe -Dcmd=compileDescribes the compile phase
mvn compiler:compileDirectly invokes the compiler plugin’s compile goal
mvn siteGenerates project site documentation and reports

Multi-module commands

CommandPurpose
mvn -pl 模块名 compileRuns a command for selected modules; replace 模块名 with the module name
mvn -am -pl 模块名 compileBuilds selected modules and their required modules
mvn -rf 模块名 packageResumes the build from a specified module after a failure

Common options

OptionPurpose
-DskipTestsSkips test execution but still compiles test code
-UForces remote update checks, often used for SNAPSHOT dependencies
-oUses only locally available dependencies and plugins in offline mode
-XPrints detailed debugging information
-P profile名Activates the specified profile; replace profile名 with its name
-T 4Uses 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