Maven 简明教程

Maven - Quick Guide

Maven - Overview

What is Maven?

Maven 是一种项目管理和理解工具,为开发人员提供了完整的构建生命周期框架。开发团队几乎可以在很短的时间内自动执行项目的构建基础设施,因为 Maven 使用了标准目录布局和默认构建生命周期。

Maven is a project management and comprehension tool that provides developers a complete build lifecycle framework. Development team can automate the project’s build infrastructure in almost no time as Maven uses a standard directory layout and a default build lifecycle.

在涉及多个开发团队的环境中,Maven 可以迅速建立按照标准工作的方式。由于大部分项目设置简单可重复利用,Maven 在创建报告、检查、构建和测试自动化设置时,简化了开发人员的工作。

In case of multiple development teams environment, Maven can set-up the way to work as per standards in a very short time. As most of the project setups are simple and reusable, Maven makes life of developer easy while creating reports, checks, build and testing automation setups.

Maven 为开发人员提供了管理以下内容的方式:

Maven provides developers ways to manage the following −

  1. Builds

  2. Documentation

  3. Reporting

  4. Dependencies

  5. SCMs

  6. Releases

  7. Distribution

  8. Mailing list

总结来说,Maven 简化并标准化了项目构建过程。它无缝处理编译、分发、文档编制、团队协作及其他任务。Maven 提高了可重复利用性,并负责大部分与构建相关的任务。

To summarize, Maven simplifies and standardizes the project build process. It handles compilation, distribution, documentation, team collaboration and other tasks seamlessly. Maven increases reusability and takes care of most of the build related tasks.

Maven Evolution

Maven 最初设计目的是简化 Jakarta Turbine 项目中的构建流程。它包含多个项目,每个项目都包含稍有不同的 ANT 构建文件。JAR 已签入 CVS。

Maven was originally designed to simplify building processes in Jakarta Turbine project. There were several projects and each project contained slightly different ANT build files. JARs were checked into CVS.

Apache 小组随后开发了 Maven ,它可以同时构建多个项目,发布项目信息,部署项目,在多个项目中共享 JAR,并协助团队协作。

Apache group then developed Maven which can build multiple projects together, publish projects information, deploy projects, share JARs across several projects and help in collaboration of teams.

Objective

Maven 的主要目标是为开发人员提供以下内容:

The primary goal of Maven is to provide developer with the following −

  1. A comprehensive model for projects, which is reusable, maintainable, and easier to comprehend.

  2. Plugins or tools that interact with this declarative model.

Maven 项目结构和内容在 XML 文件 pom.xml 中声明,该文件称为项目对象模型 (POM),它是整个 Maven 系统的基本单元。在后续章节中,我们将详细解释 POM。

Maven project structure and contents are declared in an xml file, pom.xml, referred as Project Object Model (POM), which is the fundamental unit of the entire Maven system. In later chapters, we will explain POM in detail.

Convention over Configuration

Maven 在 Convention 上使用 Configuration ,这意味着开发人员无需自己创建构建流程。

Maven uses Convention over Configuration, which means developers are not required to create build process themselves.

开发人员不必提及每个配置详情。Maven 为项目提供了可行的默认行为。当创建 Maven 项目时,Maven 将创建默认项目结构。开发人员只需要相应放置文件,而无需在 pom.xml 中定义任何配置。

Developers do not have to mention each and every configuration detail. Maven provides sensible default behavior for projects. When a Maven project is created, Maven creates default project structure. Developer is only required to place files accordingly and he/she need not to define any configuration in pom.xml.

例如,下一表格显示了项目源代码文件、资源文件和其他配置的默认值。假设 ${basedir} 表示项目位置 -

As an example, following table shows the default values for project source code files, resource files and other configurations. Assuming, ${basedir} denotes the project location −

Item

Default

source code

${basedir}/src/main/java

Resources

${basedir}/src/main/resources

Tests

${basedir}/src/test

Complied byte code

${basedir}/target

distributable JAR

${basedir}/target/classes

为了构建项目,Maven 为开发人员提供了提及生命周期目标和项目依赖项的选项(依赖于 Maven 插件功能及其默认约定)。大部分项目管理和构建相关任务均由 Maven 插件维护。

In order to build the project, Maven provides developers with options to mention life-cycle goals and project dependencies (that rely on Maven plugin capabilities and on its default conventions). Much of the project management and build related tasks are maintained by Maven plugins.

开发人员可以构建任何 Maven 项目,而无需理解各个插件的工作方式。我们在后续章节中将详细讨论 Maven 插件。

Developers can build any given Maven project without the need to understand how the individual plugins work. We will discuss Maven Plugins in detail in the later chapters.

Features of Maven

  1. Simple project setup that follows best practices.

  2. Consistent usage across all projects.

  3. Dependency management including automatic updating.

  4. A large and growing repository of libraries.

  5. Extensible, with the ability to easily write plugins in Java or scripting languages.

  6. Instant access to new features with little or no extra configuration.

  7. Model-based builds − Maven is able to build any number of projects into predefined output types such as jar, war, metadata.

  8. Coherent site of project information − Using the same metadata as per the build process, maven is able to generate a website and a PDF including complete documentation.

  9. Release management and distribution publication − Without additional configuration, maven will integrate with your source control system such as CVS and manages the release of a project.

  10. Backward Compatibility − You can easily port the multiple modules of a project into Maven 3 from older versions of Maven. It can support the older versions also.

  11. Automatic parent versioning − No need to specify the parent in the sub module for maintenance.

  12. Parallel builds − It analyzes the project dependency graph and enables you to build schedule modules in parallel. Using this, you can achieve the performance improvements of 20-50%.

  13. Better Error and Integrity Reporting − Maven improved error reporting, and it provides you with a link to the Maven wiki page where you will get full description of the error.

Maven - Environment Setup

Step 1: Verify Java Installation in Your Machine

首先,打开控制台并根据您正在使用的操作系统执行 java 命令。

First of all, open the console and execute a java command based on the operating system you are working on.

OS

Task

Command

Windows

Open Command Console

c:> java -version

Linux

Open Command Terminal

$ java -version

Mac

Open Terminal

machine:< joseph$ java -version

让我们验证所有操作系统的输出 −

Let’s verify the output for all the operating systems −

OS

Output

Windows

java 11.0.11 2021-04-20 LTS Java™ SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot™ 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

Linux

java 11.0.11 2021-04-20 LTS Java™ SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot™ 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

Mac

java 11.0.11 2021-04-20 LTS Java™ SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot™ 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

如果你尚未在你的系统中安装 Java,那么从以下链接下载 Java 软件开发套件 (SDK) http://www.oracle.com 。对于本教程,我们假设已安装 Java 11.0.11 作为版本。

If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link http://www.oracle.com. We are assuming Java 11.0.11 as the installed version for this tutorial.

Step 2: Set JAVA Environment

JAVA_HOME 环境变量设置为您计算机中安装 Java 的基本目录位置。例如。

Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example.

OS

Output

Windows

Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk11.0.11

Linux

export JAVA_HOME = /usr/local/java-current

Mac

export JAVA_HOME = /Library/Java/Home

在系统路径中追加 Java 编译器位置。

Append Java compiler location to the System Path.

OS

Output

Windows

Append the string C:\Program Files\Java\jdk11.0.11\bin at the end of the system variable, Path.

Linux

export PATH = $PATH:$JAVA_HOME/bin/

Mac

not required

如上所述,使用命令 java -version 验证 Java 安装。

Verify Java installation using the command java -version as explained above.

Step 3 - Download Maven Archive

https://maven.apache.org/download.cgi 下载 Maven 3.8.4。

Download Maven 3.8.4 from https://maven.apache.org/download.cgi.

OS

Archive name

Windows

apache-maven-3.8.4-bin.zip

Linux

apache-maven-3.8.4-bin.tar.gz

Mac

apache-maven-3.8.4-bin.tar.gz

Step 4 - Extract the Maven Archive

将存档解压到要安装 Maven 3.8.4 的目录。存档将创建一个子目录 apache-maven-3.8.4。

Extract the archive, to the directory you wish to install Maven 3.8.4. The subdirectory apache-maven-3.8.4 will be created from the archive.

OS

Location (can be different based on your installation)

Windows

C:\Program Files\Apache Software Foundation\apache-maven-3.8.4

Linux

/usr/local/apache-maven

Mac

/usr/local/apache-maven

Step 5 - Set Maven Environment Variables

将 M2_HOME、M2、MAVEN_OPTS 添加到环境变量。

Add M2_HOME, M2, MAVEN_OPTS to environment variables.

OS

Output

Windows

Set the environment variables using system properties. M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 M2=%M2_HOME%\bin MAVEN_OPTS=-Xms256m -Xmx512m

Linux

Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 export M2=$M2_HOME/bin export MAVEN_OPTS=-Xms256m -Xmx512m

Mac

Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 export M2=$M2_HOME/bin export MAVEN_OPTS=-Xms256m -Xmx512m

Step 6 - Add Maven bin Directory Location to System Path

现在将 M2 变量附加到系统路径。

Now append M2 variable to System Path.

OS

Output

Windows

Append the string ;%M2% to the end of the system variable, Path.

Linux

export PATH=$M2:$PATH

Mac

export PATH=$M2:$PATH

Step 7 - Verify Maven Installation

现在打开控制台并执行以下 mvn 命令。

Now open console and execute the following mvn command.

OS

Task

Command

Windows

Open Command Console

c:&gt; mvn --version

Linux

Open Command Terminal

$ mvn --version

Mac

Open Terminal

machine:~ joseph$ mvn --version

最后,验证上述命令的输出,其应如下所示 −

Finally, verify the output of the above commands, which should be as follows −

OS

Output

Windows

Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Maven home: C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 Java version: 11.0.11, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk11.0.11\ Default locale: en_IN, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

Linux

Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java version: 11.0.11 Java home: /usr/local/java-current/jre

Mac

Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java version: 11.0.11 Java home: /Library/Java/Home/jre

Maven - POM

POM 是 Project Object Model 的缩写。它是 Maven 中基本的工作单元。它是一个 XML 文件,作为 pom.xml 位于项目的根目录中。

POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as pom.xml.

POM 包含有关项目的信息,以及用于 Maven 构建项目的各种配置细节。

The POM contains information about the project and various configuration detail used by Maven to build the project(s).

POM 还包含目标和插件。在执行任务或目标时,Maven 会在当前目录中寻找 POM。它读取 POM,获取所需的配置信息,然后执行目标。可以在 POM 中指定的一些配置如下 −

POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, and then executes the goal. Some of the configuration that can be specified in the POM are following −

  1. project dependencies

  2. plugins

  3. goals

  4. build profiles

  5. project version

  6. developers

  7. mailing list

在创建 POM 之前,我们应该首先确定项目的 group (groupId)、其 name (artifactId) 及其版本,因为这些属性有助于在存储库中唯一地识别项目。

Before creating a POM, we should first decide the project group (groupId), its name (artifactId) and its version as these attributes help in uniquely identifying the project in repository.

POM Example

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.companyname.project-group</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
</project>

请注意,每个项目应该有一个 POM 文件。

It should be noted that there should be a single POM file for each project.

  1. All POM files require the project element and three mandatory fields: groupId, artifactId, version.

  2. Projects notation in repository is groupId:artifactId:version.

  3. Minimal requirements for a POM −

Sr.No.

Node & Description

1

Project root This is project root tag. You need to specify the basic schema settings such as apache schema and w3.org specification.

2

Model version Model version should be 4.0.0.

3

groupId This is an Id of project’s group. This is generally unique amongst an organization or a project. For example, a banking group com.company.bank has all bank related projects.

4

artifactId This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact’s location within the repository.

5

version This is the version of the project. Along with the groupId, It is used within an artifact’s repository to separate versions from each other. For example − com.company.bank:consumer-banking:1.0 com.company.bank:consumer-banking:1.1.

Super POM

超级 POM 是 Maven 的默认 POM。所有 POM 都继承自一个父 POM 或默认 POM(明确定义或未明确定义)。这个基本 POM 被称为 Super POM ,并包含默认继承的值。

The Super POM is Maven’s default POM. All POMs inherit from a parent or default (despite explicitly defined or not). This base POM is known as the Super POM, and contains values inherited by default.

Maven 使用生效 POM(超级 POM 的配置加上项目配置)来执行相关的目标。这有助于开发者在其 pom.xml 中指定最少的配置详情。尽管可以轻松地覆盖配置。

Maven use the effective POM (configuration from super pom plus project configuration) to execute relevant goal. It helps developers to specify minimum configuration detail in his/her pom.xml. Although configurations can be overridden easily.

通过运行以下命令,可以轻松查看超级 POM 的默认配置: mvn help:effective-pom

An easy way to look at the default configurations of the super POM is by running the following command: mvn help:effective-pom

在计算机的任何目录中创建一个 pom.xml。使用上面提到的示例 pom 的内容。

Create a pom.xml in any directory on your computer.Use the content of above mentioned example pom.

在以下示例中,我们在 C:\MVN\project 文件夹中创建了一个 pom.xml。

In example below, We’ve created a pom.xml in C:\MVN\project folder.

现在打开命令控制台,转到包含 pom.xml 的文件夹并执行以下 mvn 命令。

Now open command console, go the folder containing pom.xml and execute the following mvn command.

C:\MVN\project>mvn help:effective-pom

Maven 将开始处理并显示 effective-pom。

Maven will start processing and display the effective-pom.

C:\MVN>mvn help:effective-pom
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------< com.companyname.project-group:project >----------------
[INFO] Building project 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-help-plugin:3.2.0:effective-pom (default-cli) @ project ---
[INFO]
Effective POMs, after inheritance, interpolation, and profiles are applied:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.261 s
[INFO] Finished at: 2021-12-10T19:54:53+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN>

在应用继承、插入和配置文件后,Effective POM 显示为控制台的结果。

Effective POM displayed as result in console, after inheritance, interpolation, and profiles are applied.

<?xml version="1.0" encoding="Cp1252"?>
<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Generated by Maven Help Plugin on 2021-12-10T19:54:52+05:30            -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/                -->
<!--                                                                        -->
<!-- ====================================================================== -->
<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Effective POM for project                                              -->
<!-- 'com.companyname.project-group:project:jar:1.0'                        -->
<!--                                                                        -->
<!-- ====================================================================== -->
<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">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.project-group</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <repositories>
      <repository>
         <snapshots>
            <enabled>false</enabled>
         </snapshots>
         <id>central</id>
         <name>Central Repository</name>
         <url>https://repo.maven.apache.org/maven2</url>
      </repository>
   </repositories>
   <pluginRepositories>
      <pluginRepository>
         <releases>
            <updatePolicy>never</updatePolicy>
         </releases>
         <snapshots>
            <enabled>false</enabled>
         </snapshots>
         <id>central</id>
         <name>Central Repository</name>
         <url>https://repo.maven.apache.org/maven2</url>
      </pluginRepository>
   </pluginRepositories>
   <build>
      <sourceDirectory>C:\MVN\src\main\java</sourceDirectory>
      <scriptSourceDirectory>C:\MVN\src\main\scripts</scriptSourceDirectory>
      <testSourceDirectory>C:\MVN\src\test\java</testSourceDirectory>
      <outputDirectory>C:\MVN\target\classes</outputDirectory>
      <testOutputDirectory>C:\MVN\target\test-classes</testOutputDirectory>
      <resources>
         <resource>
            <directory>C:\MVN\src\main\resources</directory>
         </resource>
      </resources>
      <testResources>
         <testResource>
            <directory>C:\MVN\src\test\resources</directory>
         </testResource>
      </testResources>
      <directory>C:\MVN\target</directory>
      <finalName>project-1.0</finalName>
      <pluginManagement>
         <plugins>
            <plugin>
               <artifactId>maven-antrun-plugin</artifactId>
               <version>1.3</version>
            </plugin>
            <plugin>
               <artifactId>maven-assembly-plugin</artifactId>
               <version>2.2-beta-5</version>
            </plugin>
            <plugin>
               <artifactId>maven-dependency-plugin</artifactId>
               <version>2.8</version>
            </plugin>
            <plugin>
               <artifactId>maven-release-plugin</artifactId>
               <version>2.5.3</version>
            </plugin>
         </plugins>
      </pluginManagement>
      <plugins>
         <plugin>
            <artifactId>maven-clean-plugin</artifactId>
            <version>2.5</version>
            <executions>
               <execution>
               <id>default-clean</id>
               <phase>clean</phase>
               <goals>
                  <goal>clean</goal>
               </goals>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.6</version>
            <executions>
               <execution>
                  <id>default-testResources</id>
                  <phase>process-test-resources</phase>
                  <goals>
                     <goal>testResources</goal>
                  </goals>
               </execution>
               <execution>
                  <id>default-resources</id>
                  <phase>process-resources</phase>
                  <goals>
                     <goal>resources</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <executions>
               <execution>
                  <id>default-jar</id>
                  <phase>package</phase>
                  <goals>
                     <goal>jar</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <executions>
               <execution>
                  <id>default-compile</id>
                  <phase>compile</phase>
                  <goals>
                     <goal>compile</goal>
                  </goals>
               </execution>
               <execution>
                  <id>default-testCompile</id>
                  <phase>test-compile</phase>
                  <goals>
                     <goal>testCompile</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12.4</version>
            <executions>
               <execution>
                  <id>default-test</id>
                  <phase>test</phase>
                  <goals>
                     <goal>test</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.4</version>
            <executions>
               <execution>
                  <id>default-install</id>
                  <phase>install</phase>
                  <goals>
                     <goal>install</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.7</version>
            <executions>
               <execution>
                  <id>default-deploy</id>
                  <phase>deploy</phase>
                  <goals>
                     <goal>deploy</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.3</version>
            <executions>
               <execution>
                  <id>default-site</id>
                  <phase>site</phase>
                  <goals>
                     <goal>site</goal>
                  </goals>
                  <configuration>
                     <outputDirectory>C:\MVN\target\site</outputDirectory>
                     <reportPlugins>
                        <reportPlugin>
                           <groupId>org.apache.maven.plugins</groupId>
                           <artifactId>maven-project-info-reports-plugin</artifactId>
                        </reportPlugin>
                     </reportPlugins>
                  </configuration>
               </execution>
               <execution>
                  <id>default-deploy</id>
                  <phase>site-deploy</phase>
                  <goals>
                     <goal>deploy</goal>
                  </goals>
                  <configuration>
                     <outputDirectory>C:\MVN\target\site</outputDirectory>
                     <reportPlugins>
                        <reportPlugin>
                           <groupId>org.apache.maven.plugins</groupId>
                           <artifactId>maven-project-info-reports-plugin</artifactId>
                        </reportPlugin>
                     </reportPlugins>
                  </configuration>
               </execution>
            </executions>
            <configuration>
               <outputDirectory>C:\MVN\target\site</outputDirectory>
               <reportPlugins>
                  <reportPlugin>
                     <groupId>org.apache.maven.plugins</groupId>
                     <artifactId>maven-project-info-reports-plugin</artifactId>
                  </reportPlugin>
               </reportPlugins>
            </configuration>
         </plugin>
      </plugins>
   </build>
   <reporting>
      <outputDirectory>C:\MVN\target\site</outputDirectory>
   </reporting>
</project>

在上面的 pom.xml 中,您可以看到 Maven 在执行所需目标时将使用的默认项目源文件夹结构、输出目录、所需的插件、存储库、报告目录。

In above pom.xml, you can see the default project source folders structure, output directory, plug-ins required, repositories, reporting directory, which Maven will be using while executing the desired goals.

也不必手动编写 Maven pom.xml。Maven 提供了许多原型插件用于创建项目,依次创建项目结构和 pom.xml。

Maven pom.xml is also not required to be written manually. Maven provides numerous archetype plugins to create projects, which in order, create the project structure and pom.xml

Maven - Build Life Cycle

What is Build Lifecycle?

构建生命周期是一个定义明确的阶段序列,该序列定义了执行目标的顺序。在此,阶段表示生命周期中的一个阶段。例如,一个典型的 Maven Build Lifecycle 包含以下阶段序列。

A Build Lifecycle is a well-defined sequence of phases, which define the order in which the goals are to be executed. Here phase represents a stage in life cycle. As an example, a typical Maven Build Lifecycle consists of the following sequence of phases.

Phase

Handles

Description

prepare-resources

resource copying

Resource copying can be customized in this phase.

validate

Validating the information

Validates if the project is correct and if all necessary information is available.

compile

compilation

Source code compilation is done in this phase.

Test

Testing

Tests the compiled source code suitable for testing framework.

package

packaging

This phase creates the JAR/WAR package as mentioned in the packaging in POM.xml.

install

installation

This phase installs the package in local/remote maven repository.

Deploy

Deploying

Copies the final package to the remote repository.

始终都有 prepost 阶段来注册 goals ,这些阶段必须在特定阶段之前或之后运行。

There are always pre and post phases to register goals, which must run prior to, or after a particular phase.

当 Maven 开始构建项目时,它会逐步执行一系列已定义的阶段并执行目标,这些目标已注册到各个阶段。

When Maven starts building a project, it steps through a defined sequence of phases and executes goals, which are registered with each phase.

Maven 具有以下三个标准生命周期−

Maven has the following three standard lifecycles −

  1. clean

  2. default(or build)

  3. site

goal 表示一项有助于构建和管理项目,并可能绑定到一个或多个构建阶段的特定任务。未绑定到任何构建阶段的目标可以通过直接调用在构建生命周期之外执行。

A goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation.

执行顺序取决于目标和构建阶段的调用顺序。例如,考虑以下命令。 cleanpackage 参数是构建阶段,而 dependency:copy-dependencies 是目标。

The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example, consider the command below. The clean and package arguments are build phases while the dependency:copy-dependencies is a goal.

mvn clean dependency:copy-dependencies package

此处将首先执行 clean 阶段,然后执行 dependency:copy-dependencies goal ,最后执行 package 阶段。

Here the clean phase will be executed first, followed by the dependency:copy-dependencies goal, and finally package phase will be executed.

Clean Lifecycle

当我们执行 mvn post-clean 命令时,Maven 将调用包含以下阶段的 clean 生命周期。

When we execute mvn post-clean command, Maven invokes the clean lifecycle consisting of the following phases.

  1. pre-clean

  2. clean

  3. post-clean

Maven clean 目标 (clean:clean) 绑定到 clean 生命周期中的 clean 阶段。它的 clean:cleangoal 通过删除构建目录来删除构建结果。因此,当执行 mvn clean 命令时,Maven 将删除构建目录。

Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:cleangoal deletes the output of a build by deleting the build directory. Thus, when mvn clean command executes, Maven deletes the build directory.

我们可以通过在 clean 生命周期中的任何上述阶段中指定目标来自定义此行为。

We can customize this behavior by mentioning goals in any of the above phases of clean life cycle.

在以下示例中,我们将 maven-antrun-plugin:run 目标附加到 pre-clean、clean 和 post-clean 阶段。这将允许我们回显显示 clean 生命周期各个阶段的文本消息。

In the following example, We’ll attach maven-antrun-plugin:run goal to the pre-clean, clean, and post-clean phases. This will allow us to echo text messages displaying the phases of the clean lifecycle.

我们在 C:\MVN\project 文件夹中创建了一个 pom.xml。

We’ve created a pom.xml in C:\MVN\project folder.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.projectgroup</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.1</version>
            <executions>
               <execution>
                  <id>id.pre-clean</id>
                  <phase>pre-clean</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>pre-clean phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.clean</id>
                  <phase>clean</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>clean phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.post-clean</id>
                  <phase>post-clean</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>post-clean phase</echo>
                     </tasks>
                  </configuration>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>
</project>

现在,打开命令控制台,转到包含 pom.xml 的文件夹,并执行以下 mvn 命令。

Now open command console, go to the folder containing pom.xml and execute the following mvn command.

C:\MVN\project>mvn post-clean

Maven 将开始处理并显示 clean 生命周期中的所有阶段。

Maven will start processing and displaying all the phases of clean life cycle.

C:\MVN>mvn post-clean
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< com.companyname.projectgroup:project >----------------
[INFO] Building project 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-antrun-plugin:1.1:run (id.pre-clean) @ project ---
[INFO] Executing tasks
     [echo] pre-clean phase
[INFO] Executed tasks
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ project ---
[INFO]
[INFO] --- maven-antrun-plugin:1.1:run (id.clean) @ project ---
[INFO] Executing tasks
     [echo] clean phase
[INFO] Executed tasks
[INFO]
[INFO] --- maven-antrun-plugin:1.1:run (id.post-clean) @ project ---
[INFO] Executing tasks
     [echo] post-clean phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.740 s
[INFO] Finished at: 2021-12-10T20:03:53+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN>

您可以尝试调整 mvn clean 命令,该命令将显示 pre-clean 和 clean。没有 post-clean 阶段将被执行。

You can try tuning mvn clean command, which will display pre-clean and clean. Nothing will be executed for post-clean phase.

Default (or Build) Lifecycle

这是 Maven 的主要生命周期,用于构建应用程序。它具有以下 21 个阶段。

This is the primary life cycle of Maven and is used to build the application. It has the following 21 phases.

Sr.No.

Lifecycle Phase & Description

1

validate Validates whether project is correct and all necessary information is available to complete the build process.

2

initialize Initializes build state, for example set properties.

3

generate-sources Generate any source code to be included in compilation phase.

4

process-sources Process the source code, for example, filter any value.

5

generate-resources Generate resources to be included in the package.

6

process-resources Copy and process the resources into the destination directory, ready for packaging phase.

7

compile Compile the source code of the project.

8

process-classes Post-process the generated files from compilation, for example to do bytecode enhancement/optimization on Java classes.

9

generate-test-sources Generate any test source code to be included in compilation phase.

10

process-test-sources Process the test source code, for example, filter any values.

11

test-compile Compile the test source code into the test destination directory.

12

process-test-classes Process the generated files from test code file compilation.

13

test Run tests using a suitable unit testing framework (Junit is one).

14

prepare-package Perform any operations necessary to prepare a package before the actual packaging.

15

package Take the compiled code and package it in its distributable format, such as a JAR, WAR, or EAR file.

16

pre-integration-test Perform actions required before integration tests are executed. For example, setting up the required environment.

17

integration-test Process and deploy the package if necessary into an environment where integration tests can be run.

18

post-integration-test Perform actions required after integration tests have been executed. For example, cleaning up the environment.

19

verify Run any check-ups to verify the package is valid and meets quality criteria.

20

install Install the package into the local repository, which can be used as a dependency in other projects locally.

21

deploy Copies the final package to the remote repository for sharing with other developers and projects.

以下是几个与 Maven 生命周期相关的概念,值得提及:

There are few important concepts related to Maven Lifecycles, which are worth to mention −

  1. When a phase is called via Maven command, for example mvn compile, only phases up to and including that phase will execute.

  2. Different maven goals will be bound to different phases of Maven lifecycle depending upon the type of packaging (JAR / WAR / EAR).

在以下示例中,我们将 maven-antrun-plugin:run 目标附加到构建生命周期的几个阶段。这将允许我们通过回显文本消息来显示生命周期的阶段。

In the following example, we will attach maven-antrun-plugin:run goal to few of the phases of Build lifecycle. This will allow us to echo text messages displaying the phases of the lifecycle.

我们在 C:\MVN\project 文件夹中更新了 pom.xml。

We’ve updated pom.xml in C:\MVN\project folder.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.projectgroup</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.1</version>
            <executions>
               <execution>
                  <id>id.validate</id>
                  <phase>validate</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>validate phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.compile</id>
                  <phase>compile</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>compile phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.test</id>
                  <phase>test</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>test phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.package</id>
                  <phase>package</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>package phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.deploy</id>
                  <phase>deploy</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>deploy phase</echo>
                     </tasks>
                  </configuration>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>
</project>

现在打开命令控制台,转到包含 pom.xml 的文件夹并执行以下 mvn 命令。

Now open command console, go the folder containing pom.xml and execute the following mvn command.

C:\MVN\project>mvn compile

Maven 将开始处理并显示构建生命周期中直至编译阶段的阶段。

Maven will start processing and display phases of build life cycle up to the compile phase.

C:\MVN>mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< com.companyname.projectgroup:project >----------------
[INFO] Building project 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-antrun-plugin:1.1:run (id.validate) @ project ---
[INFO] Executing tasks
     [echo] validate phase
[INFO] Executed tasks
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ project ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ project ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-antrun-plugin:1.1:run (id.compile) @ project ---
[INFO] Executing tasks
     [echo] compile phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.033 s
[INFO] Finished at: 2021-12-10T20:05:46+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN>

Site Lifecycle

Maven Site 插件通常用于创建新文档来创建报告、部署站点等。它具有以下阶段 -

Maven Site plugin is generally used to create fresh documentation to create reports, deploy site, etc. It has the following phases −

  1. pre-site

  2. site

  3. post-site

  4. site-deploy

在以下示例中,我们将 maven-antrun-plugin:run 目标附加到 Site 生命周期所有阶段。这将允许我们通过回显文本消息来显示生命周期的阶段。

In the following example, we will attach maven-antrun-plugin:run goal to all the phases of Site lifecycle. This will allow us to echo text messages displaying the phases of the lifecycle.

我们在 C:\MVN\project 文件夹中更新了 pom.xml。

We’ve updated pom.xml in C:\MVN\project folder.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.projectgroup</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.7</version>
         </plugin>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-project-info-reports-plugin</artifactId>
            <version>2.9</version>
         </plugin>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.1</version>
            <executions>
               <execution>
                  <id>id.pre-site</id>
                  <phase>pre-site</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>pre-site phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.site</id>
                  <phase>site</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>site phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.post-site</id>
                  <phase>post-site</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>post-site phase</echo>
                     </tasks>
                  </configuration>
               </execution>

               <execution>
                  <id>id.site-deploy</id>
                  <phase>site-deploy</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>site-deploy phase</echo>
                     </tasks>
                  </configuration>
               </execution>

            </executions>
         </plugin>
      </plugins>
   </build>
</project>

现在打开命令控制台,转到包含 pom.xml 的文件夹并执行以下 mvn 命令。

Now open the command console, go the folder containing pom.xml and execute the following mvn command.

C:\MVN\project>mvn site

Maven 将开始处理并显示站点生命周期中直至站点阶段的阶段。

Maven will start processing and displaying the phases of site life cycle up to site phase.

C:\MVN>mvn site
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< com.companyname.projectgroup:project >----------------
[INFO] Building project 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-antrun-plugin:3.0.0:run (id.pre-site) @ project ---
[INFO] Executing tasks
[WARNING]      [echo] pre-site phase
[INFO] Executed tasks
[INFO]
[INFO] --- maven-site-plugin:3.7:site (default-site) @ project ---
[WARNING] Input file encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[WARNING] No project URL defined - decoration links will not be relativized!
[INFO] Rendering site with org.apache.maven.skins:maven-default-skin:jar:1.2 skin.
[INFO]
[INFO] --- maven-antrun-plugin:3.0.0:run (id.site) @ project ---
[INFO] Executing tasks
[WARNING]      [echo] site phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.323 s
[INFO] Finished at: 2021-12-10T20:22:31+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN>

Maven - Build Profiles

What is Build Profile?

构建配置文件是一组配置值,可用于设置或覆盖 Maven 构建的默认值。使用构建配置文件,可以针对不同环境(如生产环境与开发环境)自定义构建。

A Build profile is a set of configuration values, which can be used to set or override default values of Maven build. Using a build profile, you can customize build for different environments such as Production v/s Development environments.

配置文件在 pom.xml 文件中使用其 activeProfiles/profiles 元素指定,并且以多种方式触发。配置文件在构建时修改 POM,并且用于向不同的目标环境提供参数(例如,开发、测试和生产环境中的数据库服务器的路径)。

Profiles are specified in pom.xml file using its activeProfiles/profiles elements and are triggered in variety of ways. Profiles modify the POM at build time, and are used to give parameters different target environments (for example, the path of the database server in the development, testing, and production environments).

Types of Build Profile

构建配置文件主要分为三种类型。

Build profiles are majorly of three types.

Type

Where it is defined

Per Project

Defined in the project POM file, pom.xml

Per User

Defined in Maven settings xml file (%USER_HOME%/.m2/settings.xml)

Global

Defined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)

Profile Activation

Maven 构建配置文件可以通过多种方式激活。

A Maven Build Profile can be activated in various ways.

  1. Explicitly using command console input.

  2. Through maven settings.

  3. Based on environment variables (User/System variables).

  4. OS Settings (for example, Windows family).

  5. Present/missing files.

Profile Activation Examples

让我们假设项目的目录结构如下 −

Let us assume the following directory structure of your project −

structure

现在,在 src/main/resources 下,有三个特定于环境的文件 −

Now, under src/main/resources, there are three environment specific files −

Sr.No.

File Name & Description

1

env.properties default configuration used if no profile is mentioned.

2

env.test.properties test configuration when test profile is used.

3

env.prod.properties production configuration when prod profile is used.

Explicit Profile Activation

在以下示例中,我们将附加 maven-antrun-plugin:run 目标以测试阶段。这将允许我们为不同的配置文件回显文本消息。我们将使用 pom.xml 定义不同的配置文件,并将使用 maven 命令在命令台中激活配置文件。

In the following example, we will attach maven-antrun-plugin:run goal to test the phase. This will allow us to echo text messages for different profiles. We will be using pom.xml to define different profiles and will activate profile at command console using maven command.

假设我们已在 C:\MVN\project 文件夹中创建了以下 pom.xml。

Assume, we’ve created the following pom.xml in C:\MVN\project folder.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.projectgroup</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <profiles>
      <profile>
         <id>test</id>
         <build>
            <plugins>
               <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-antrun-plugin</artifactId>
                  <version>1.1</version>
                  <executions>
                     <execution>
                        <phase>test</phase>
                        <goals>
                           <goal>run</goal>
                        </goals>
                        <configuration>
                           <tasks>
                              <echo>Using env.test.properties</echo>
                              <copy file="src/main/resources/env.test.properties"
                                 tofile="${project.build.outputDirectory}/env.properties"/>
                           </tasks>
                        </configuration>
                     </execution>
                  </executions>
               </plugin>
            </plugins>
         </build>
      </profile>
   </profiles>
</project>

现在打开命令台,转到包含 pom.xml 的文件夹,并执行以下 mvn 命令。使用 -P 选项将配置文件名传递为参数。

Now open the command console, go to the folder containing pom.xml and execute the following mvn command. Pass the profile name as argument using -P option.

C:\MVN\project>mvn test -Ptest

Maven 将开始处理并显示测试构建配置文件的结果。

Maven will start processing and displaying the result of test build profile.

C:\MVN>mvn test -Ptest
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< com.companyname.projectgroup:project >----------------
[INFO] Building project 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ project ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ project ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ project ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ project ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ project ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-antrun-plugin:1.1:run (default) @ project ---
[INFO] Executing tasks
     [echo] Using env.test.properties
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.011 s
[INFO] Finished at: 2021-12-10T20:29:39+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN>

现在作为一项练习,您可以执行以下步骤:

Now as an exercise, you can perform the following steps −

  1. Add another profile element to profiles element of pom.xml (copy existing profile element and paste it where profile elements ends).

  2. Update id of this profile element from test to normal.

  3. Update task section to echo env.properties and copy env.properties to target directory.

  4. Again repeat the above three steps, update id to prod and task section for env.prod.properties.

  5. That’s all. Now you’ve three build profiles ready (normal/test/prod).

现在打开命令台,转到包含 pom.xml 的文件夹,并执行以下 mvn 命令。使用 -P 选项将配置文件名称作为参数传递。

Now open the command console, go to the folder containing pom.xml and execute the following mvn commands. Pass the profile names as argument using -P option.

C:\MVN\project>mvn test -Pnormal

C:\MVN\project>mvn test -Pprod

检查构建的输出以查看差异。

Check the output of the build to see the difference.

Profile Activation via Maven Settings

打开位于 %USER_HOME%/.m2 目录中的 Maven settings.xml 文件,其中 %USER_HOME% 表示用户主目录。如果 settings.xml 文件不存在,则创建一个新文件。

Open Maven settings.xml file available in %USER_HOME%/.m2 directory where %USER_HOME% represents the user home directory. If settings.xml file is not there, then create a new one.

添加测试配置文件,并使用活动配置文件节点将其作为活动配置文件,如下例所示。

Add test profile as an active profile using active Profiles node as shown below in example.

<settings 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
   http://maven.apache.org/xsd/settings-1.0.0.xsd">
   <mirrors>
      <mirror>
         <id>maven.dev.snaponglobal.com</id>
         <name>Internal Artifactory Maven repository</name>
         <url>http://repo1.maven.org/maven2/</url>
         <mirrorOf>*</mirrorOf>
      </mirror>
   </mirrors>
   <activeProfiles>
      <activeProfile>test</activeProfile>
   </activeProfiles>
</settings>

现在打开命令台,转到包含 pom.xml 的文件夹,并执行以下 mvn 命令。不要使用 -P 选项传递配置文件名称。Maven 将显示测试配置文件成为活动配置文件的结果。

Now open command console, go to the folder containing pom.xml and execute the following mvn command. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile.

C:\MVN\project>mvn test

Profile Activation via Environment Variables

现在从 maven settings.xml 中删除活动配置文件,并更新 pom.xml 中提到的测试配置文件。将 activation 元素添加到配置文件元素,如下所示。

Now remove active profile from maven settings.xml and update the test profile mentioned in pom.xml. Add activation element to profile element as shown below.

当使用值“测试”指定系统属性"env"时,测试配置文件将触发。创建环境变量“env”,并将它的值设置为“测试”。

The test profile will trigger when the system property "env" is specified with the value "test". Create an environment variable "env" and set its value as "test".

<profile>
   <id>test</id>
   <activation>
      <property>
         <name>env</name>
         <value>test</value>
      </property>
   </activation>
</profile>

让我们打开命令控制台,转到包含 pom.xml 的文件夹,然后执行以下 mvn 命令。

Let’s open command console, go to the folder containing pom.xml and execute the following mvn command.

C:\MVN\project>mvn test

Profile Activation via Operating System

激活元素将操作系统详细信息包含在内,如下所示。当系统是 Windows XP 时,此测试配置文件将触发。

Activation element to include os detail as shown below. This test profile will trigger when the system is windows XP.

<profile>
   <id>test</id>
   <activation>
      <os>
         <name>Windows XP</name>
         <family>Windows</family>
         <arch>x86</arch>
         <version>5.1.2600</version>
      </os>
   </activation>
</profile>

现在打开命令控制台,转到包含 pom.xml 的文件夹,然后执行以下 mvn 命令。不使用 -P 选项传递配置文件名。Maven 将显示测试配置文件是处于活动状态的结果。

Now open command console, go to the folder containing pom.xml and execute the following mvn commands. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile.

C:\MVN\project>mvn test

Profile Activation via Present/Missing File

现在激活元素将操作系统详细信息包含在内,如下所示。当 target/generated-sources/axistools/wsdl2java/com/companyname/group 缺失时,测试配置文件将触发。

Now activation element to include OS details as shown below. The test profile will trigger when target/generated-sources/axistools/wsdl2java/com/companyname/group is missing.

<profile>
   <id>test</id>
   <activation>
      <file>
         <missing>target/generated-sources/axistools/wsdl2java/
           com/companyname/group</missing>
      </file>
   </activation>
</profile>

现在打开命令控制台,转到包含 pom.xml 的文件夹,然后执行以下 mvn 命令。不使用 -P 选项传递配置文件名。Maven 将显示测试配置文件是处于活动状态的结果。

Now open the command console, go to the folder containing pom.xml and execute the following mvn commands. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile.

C:\MVN\project>mvn test

Maven - Repositories

What is a Maven Repository?

在 Maven 术语中,存储库是一个存储所有项目 jar、库 jar、插件或任何其他项目特定构件的目录,Maven 可以在其中轻松使用它们。

In Maven terminology, a repository is a directory where all the project jars, library jar, plugins or any other project specific artifacts are stored and can be used by Maven easily.

Maven 存储库有三种类型。以下说明将介绍这三种类型的相关概念。

Maven repository are of three types. The following illustration will give an idea regarding these three types.

  1. local

  2. central

  3. remote

repository structure

Local Repository

Maven 本地存储库是计算机上的一个文件夹位置。首次运行任何 maven 命令时将创建它。

Maven local repository is a folder location on your machine. It gets created when you run any maven command for the first time.

Maven 本地存储库保存项目的所有依赖项(库 jar、插件 jar 等)。运行 Maven 构建时,Maven 会自动将所有依赖项 jar 下载到本地存储库中。这有助于避免每次构建项目时引用存储在远程计算机上的依赖项。

Maven local repository keeps your project’s all dependencies (library jars, plugin jars etc.). When you run a Maven build, then Maven automatically downloads all the dependency jars into the local repository. It helps to avoid references to dependencies stored on remote machine every time a project is build.

默认情况下,Maven会在 %USER_HOME% 目录中创建 Maven 本地存储库。要覆盖默认位置,请在 %M2_HOME%\conf 目录中提供的 Maven settings.xml 文件中指定另一路径。

Maven local repository by default get created by Maven in %USER_HOME% directory. To override the default location, mention another path in Maven settings.xml file available at %M2_HOME%\conf directory.

<settings xmlns = "http://maven.apache.org/SETTINGS/1.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/SETTINGS/1.0.0
   http://maven.apache.org/xsd/settings-1.0.0.xsd">
   <localRepository>C:/MyLocalRepository</localRepository>
</settings>

运行 Maven 命令时,Maven 会将依赖项下载到自定义路径。

When you run Maven command, Maven will download dependencies to your custom path.

Central Repository

Maven 中央存储库是由 Maven 社区提供的存储库。它包含大量常用库。

Maven central repository is repository provided by Maven community. It contains a large number of commonly used libraries.

当 Maven 在本地存储库中找不到任何依赖项时,它会使用以下 URL 在中央存储库中开始搜索: https://repo1.maven.org/maven2/

When Maven does not find any dependency in local repository, it starts searching in central repository using following URL − https://repo1.maven.org/maven2/

中央存储库的关键概念如下:

Key concepts of Central repository are as follows −

  1. This repository is managed by Maven community.

  2. It is not required to be configured.

  3. It requires internet access to be searched.

为了浏览中央 Maven 存储库的内容,Maven 社区提供了 URL − https://search.maven.org/#browse 。使用此库,开发人员可以搜索中央存储库中所有可用的库。

To browse the content of central maven repository, maven community has provided a URL − https://search.maven.org/#browse. Using this library, a developer can search all the available libraries in central repository.

Remote Repository

有时,Maven 也找不到中央存储库中提到的依赖项。然后它会停止构建过程,并向控制台输出错误消息。为了防止这种情况,Maven 提供了 Remote Repository 的概念,它是开发人员自己的自定义存储库,其中包含所需的库或其他项目 jar。

Sometimes, Maven does not find a mentioned dependency in central repository as well. It then stops the build process and output error message to console. To prevent such situation, Maven provides concept of Remote Repository, which is developer’s own custom repository containing required libraries or other project jars.

例如,使用下面提到的 POM.xml,Maven 将从在同一 pom.xml 中提到的远程存储库中下载依赖项(在中央存储库中不可用)。

For example, using below mentioned POM.xml, Maven will download dependency (not available in central repository) from Remote Repositories mentioned in the same pom.xml.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.projectgroup</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <dependencies>
      <dependency>
         <groupId>com.companyname.common-lib</groupId>
         <artifactId>common-lib</artifactId>
         <version>1.0.0</version>
      </dependency>
   <dependencies>
   <repositories>
      <repository>
         <id>companyname.lib1</id>
         <url>http://download.companyname.org/maven2/lib1</url>
      </repository>
      <repository>
         <id>companyname.lib2</id>
         <url>http://download.companyname.org/maven2/lib2</url>
      </repository>
   </repositories>
</project>

Maven Dependency Search Sequence

当我们执行 Maven 构建命令时,Maven 将按以下顺序开始查找依赖库 −

When we execute Maven build commands, Maven starts looking for dependency libraries in the following sequence −

  1. Step 1 − Search dependency in local repository, if not found, move to step 2 else perform the further processing.

  2. Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4. Else it is downloaded to local repository for future reference.

  3. Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency).

  4. Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference. Otherwise, Maven stops processing and throws error (Unable to find dependency).

Maven - Plugins

What are Maven Plugins?

Maven 实际上是一个插件执行框架,其中的每一项任务都是由插件执行。Maven 插件通常用于:-

Maven is actually a plugin execution framework where every task is actually done by plugins. Maven Plugins are generally used to −

  1. create jar file

  2. create war file

  3. compile code files

  4. unit testing of code

  5. create project documentation

  6. create project reports

一个插件通常提供一组目标,这些目标可以使用以下语法执行:-

A plugin generally provides a set of goals, which can be executed using the following syntax −

mvn [plugin-name]:[goal-name]

例如,可以通过运行以下命令,使用 maven-compiler-plugin 的 compile-goal 编译一个 Java 项目。

For example, a Java project can be compiled with the maven-compiler-plugin’s compile-goal by running the following command.

mvn compiler:compile

Plugin Types

Maven 提供了以下两种类型的插件:-

Maven provided the following two types of Plugins −

Sr.No.

Type & Description

1

Build plugins They execute during the build process and should be configured in the <build/> element of pom.xml.

2

Reporting plugins They execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml.

以下是几个常见插件的列表:-

Following is the list of few common plugins −

Sr.No.

Plugin & Description

1

clean Cleans up target after the build. Deletes the target directory.

2

compiler Compiles Java source files.

3

surefire Runs the JUnit unit tests. Creates test reports.

4

jar Builds a JAR file from the current project.

5

war Builds a WAR file from the current project.

6

javadoc Generates Javadoc for the project.

7

antrun Runs a set of ant tasks from any phase mentioned of the build.

Example

我们在示例中大量使用 maven-antrun-plugin 在控制台上打印数据。参考构建配置文件章节。让我们进一步了解一下它,并在 C:\MVN\project 文件夹中创建一个 pom.xml。

We’ve used maven-antrun-plugin extensively in our examples to print data on console. Refer Build Profiles chapter. Let us understand it in a better way and create a pom.xml in C:\MVN\project folder.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.projectgroup</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.1</version>
            <executions>
               <execution>
                  <id>id.clean</id>
                  <phase>clean</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>clean phase</echo>
                     </tasks>
                  </configuration>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>
</project>

接下来,打开命令控制台并转到包含 pom.xml 的文件夹,然后执行以下 mvn 命令。

Next, open the command console and go to the folder containing pom.xml and execute the following mvn command.

C:\MVN\project>mvn clean

Maven 将开始处理并显示 clean 生命周期中的 clean phase。

Maven will start processing and displaying the clean phase of clean life cycle.

C:\MVN>mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< com.companyname.projectgroup:project >----------------
[INFO] Building project 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ project ---
[INFO] Deleting C:\MVN\target
[INFO]
[INFO] --- maven-antrun-plugin:1.1:run (id.clean) @ project ---
[INFO] Executing tasks
     [echo] clean phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.266 s
[INFO] Finished at: 2021-12-13T13:58:10+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN>

上述示例说明了以下几个关键概念:-

The above example illustrates the following key concepts −

  1. Plugins are specified in pom.xml using plugins element.

  2. Each plugin can have multiple goals.

  3. You can define phase from where plugin should starts its processing using its phase element. We’ve used clean phase.

  4. You can configure tasks to be executed by binding them to goals of plugin. We’ve bound echo task with run goal of maven-antrun-plugin.

  5. Maven will then download the plugin if not available in local repository and start its processing.

Maven - Creating Project

Maven 使用 archetype 插件创建项目。为了创建简单的 Java 应用程序,我们将使用 maven-archetype-quickstart 插件。在下面的示例中,我们将使用 C:\MVN 文件夹创建一个基于 maven 的 java 应用程序项目。

Maven uses archetype plugins to create projects. To create a simple java application, we’ll use maven-archetype-quickstart plugin. In example below, we’ll create a maven based java application project in C:\MVN folder.

让我们打开命令控制台,进入 C:\MVN 目录并执行以下 mvn 命令。确保在运行命令之前 C:\MVN 目录处于空状态。

Let’s open the command console, go to the C:\MVN directory and execute the following mvn command. Make sure that C:\MVN directory is empty before running the command.

C:\MVN>mvn archetype:generate
-DgroupId = com.companyname.bank
-DartifactId = consumerBanking
-DarchetypeArtifactId = maven-archetype-quickstart
-DinteractiveMode = false

Maven 将开始处理并创建完整的 Java 应用程序项目结构。

Maven will start processing and will create the complete java application project structure.

C:\MVN>mvn archetype:generate -DgroupId=com.companyname.bank -DartifactId=consumerBanking -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: package, Value: com.companyname.bank
[INFO] Parameter: groupId, Value: com.companyname.bank
[INFO] Parameter: artifactId, Value: consumerBanking
[INFO] Parameter: packageName, Value: com.companyname.bank
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\consumerBanking
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  9.396 s
[INFO] Finished at: 2021-12-13T15:13:00+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN>

现在,进入 C:/MVN 目录。你将看到一个名为“消费者银行”(在 artifactId 中指定)的 Java 应用程序项目已创建。Maven 使用下面所示的标准目录布局 −

Now go to C:/MVN directory. You’ll see a java application project created, named consumer Banking (as specified in artifactId). Maven uses a standard directory layout as shown below −

project structure

使用上述示例,我们可以了解到以下关键概念 −

Using the above example, we can understand the following key concepts −

Sr.No.

Folder Structure & Description

1

consumerBanking contains src folder and pom.xml

2

src/main/java contains java code files under the package structure (com/companyName/bank).

3

src/main/test contains test java code files under the package structure (com/companyName/bank).

4

src/main/resources it contains images/properties files (In above example, we need to create this structure manually).

如果你仔细观察,你会发现 Maven 还会创建一个示例 Java 源文件和 Java 测试文件。打开 C:\MVN\consumerBanking\src\main\java\com\companyname\bank 文件夹,你将看到 App.java。

If you observe, you will find that Maven also created a sample Java Source file and Java Test file. Open C:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, you will see App.java.

package com.companyname.bank;

/**
 * Hello world!
 *
 */
public class App {
   public static void main( String[] args ){
      System.out.println( "Hello World!" );
   }
}

打开 C:\MVN\consumerBanking\src\test\java\com\companyname\bank 文件夹,查看 AppTest.java

Open C:\MVN\consumerBanking\src\test\java\com\companyname\bank folder to see AppTest.java.

package com.companyname.bank;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest extends TestCase {
   /**
   * Create the test case
   *
   * @param testName name of the test case
   */
   public AppTest( String testName ) {
      super( testName );
   }

   /**
   * @return the suite of tests being tested
   */
   public static Test suite() {
      return new TestSuite( AppTest.class );
   }

   /**
   * Rigourous Test :-)
   */
   public void testApp() {
      assertTrue( true );
   }
}

开发人员需要按照上表中所述放置自己的文件,Maven 会处理所有与构建相关的复杂性。

Developers are required to place their files as mentioned in table above and Maven handles all the build related complexities.

在下一章中,我们将讨论如何使用 maven 构建和测试项目,即构建和测试项目。

In the next chapter, we’ll discuss how to build and test the project using maven Build and Test Project.

Maven - Build & Test Project

我们在项目创建章节中学到的内容是如何使用 Maven 创建 Java 应用程序。现在,我们将了解如何构建和测试应用程序。

What we learnt in Project Creation chapter is how to create a Java application using Maven. Now we’ll see how to build and test the application.

转到 C:/MVN 目录(你在其中创建 Java 应用程序)。打开 consumerBanking 文件夹。你将看到 POM.xml 文件,其中包含下列内容。更新它以反映当前的 Java 版本。

Go to C:/MVN directory where you’ve created your java application. Open consumerBanking folder. You will see the POM.xml file with the following contents. Update it to reflect the current java version.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.projectgroup</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <properties>
      <maven.compiler.source>11</maven.compiler.source>
      <maven.compiler.target>11</maven.compiler.target>
   </properties>
   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
      </dependency>
   </dependencies>
</project>

这里你可以看到,Maven 已将 Junit 作为测试框架添加进来。在先前章节中所讨论的那样,默认情况下,Maven 会在其默认目录结构中添加源文件 App.java 和测试文件 AppTest.java

Here you can see, Maven already added Junit as test framework. By default, Maven adds a source file App.java and a test file AppTest.java in its default directory structure, as discussed in the previous chapter.

让我们打开命令控制台,转到 C:\MVN\consumerBanking 目录,然后执行以下 mvn 命令。

Let’s open the command console, go the C:\MVN\consumerBanking directory and execute the following mvn command.

C:\MVN\consumerBanking>mvn clean package

Maven 将开始构建该项目。

Maven will start building the project.

C:\MVN\consumerBanking>mvn clean package
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< com.companyname.bank:consumerBanking >----------------
[INFO] Building consumerBanking 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ consumerBanking ---
[INFO] Deleting C:\MVN\consumerBanking\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ consumerBanking ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ consumerBanking ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ consumerBanking ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ consumerBanking ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ consumerBanking ---
[INFO] Surefire report directory: C:\MVN\consumerBanking\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.companyname.bank.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ consumerBanking ---
[INFO] Building jar: C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.663 s
[INFO] Finished at: 2021-12-13T17:34:27+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN\consumerBanking>

你已构建自己的项目并创建了最终 jar 文件,以下是关键学习概念 −

You’ve built your project and created final jar file, following are the key learning concepts −

  1. We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package).

  2. Packaged jar is available in consumerBanking\target folder as consumerBanking-1.0-SNAPSHOT.jar.

  3. Test reports are available in consumerBanking\target\surefire-reports folder.

  4. Maven compiles the source code file(s) and then tests the source code file(s).

  5. Then Maven runs the test cases.

  6. Finally, Maven creates the package.

现在打开命令行控制台,转到 C:\MVN\consumerBanking\target\classes 目录,并执行以下 java 命令。

Now open the command console, go the C:\MVN\consumerBanking\target\classes directory and execute the following java command.

>java com.companyname.bank.App

您将看到如下结果 −

You will see the result as follows −

Hello World!

Adding Java Source Files

让我们看看如何在项目中添加其他 Java 文件。打开 C:\MVN\consumerBanking\src\main\java\com\companyname\bank 文件夹,其中创建名为 Util.java 的 Util 类。

Let’s see how we can add additional Java files in our project. Open C:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, create Util class in it as Util.java.

package com.companyname.bank;

public class Util {
   public static void printMessage(String message){
      System.out.println(message);
   }
}

更新 App 类,使用 Util 类。

Update the App class to use Util class.

package com.companyname.bank;

/**
* Hello world!
*
*/

public class App {
   public static void main( String[] args ){
      Util.printMessage("Hello World!");
   }
}

现在打开命令行控制台,转到 C:\MVN\consumerBanking 目录,并执行以下 mvn 命令。

Now open the command console, go the C:\MVN\consumerBanking directory and execute the following mvn command.

>mvn clean compile

Maven 构建成功后,转到 C:\MVN\consumerBanking\target\classes 目录并执行以下 java 命令。

After Maven build is successful, go to the C:\MVN\consumerBanking\target\classes directory and execute the following java command.

>java -cp com.companyname.bank.App

您将看到如下结果 −

You will see the result as follows −

Hello World!

Maven - External Dependencies

如你所知,Maven 使用存储库概念完成依赖管理。但如果依赖项在任何远程存储库和中央存储库中都不可用,会发生什么情况呢?Maven 使用 External Dependency 的概念为这种情况提供了答案。

As you know, Maven does the dependency management using the concept of Repositories. But what happens if dependency is not available in any of remote repositories and central repository? Maven provides answer for such scenario using concept of External Dependency.

例如,让我们对在“创建 Java 项目”章节中创建的项目进行以下更改。

For example, let us do the following changes to the project created in ‘Creating Java Project’ chapter.

  1. Add lib folder to the src folder.

  2. Copy any jar into the lib folder. We’ve used ldapjdk.jar, which is a helper library for LDAP operations.

现在我们的项目结构应如下所示 −

Now our project structure should look like the following −

external project structure

这里,您拥有自己的特定于项目的库,这是一个常见的情况,它包含 jar 文件,Maven 可能无法从任何存储库中下载这些 jar 文件。如果您的代码使用 Maven 使用此库,则 Maven 构建将失败,因为它在编译阶段无法下载或引用此库。

Here you are having your own library, specific to the project, which is an usual case and it contains jars, which may not be available in any repository for maven to download from. If your code is using this library with Maven, then Maven build will fail as it cannot download or refer to this library during compilation phase.

为了处理这种情况,让我们使用以下方法将此外部依赖项添加到 maven pom.xml

To handle the situation, let’s add this external dependency to maven pom.xml using the following way.

<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
   http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.bank</groupId>
   <artifactId>consumerBanking</artifactId>
   <packaging>jar</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>consumerBanking</name>
   <url>http://maven.apache.org</url>

   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>ldapjdk</groupId>
         <artifactId>ldapjdk</artifactId>
         <scope>system</scope>
         <version>1.0</version>
         <systemPath>${basedir}\src\lib\ldapjdk.jar</systemPath>
      </dependency>
   </dependencies>

</project>

查看上面的示例中 dependencies 依赖项下面的第二个依赖项元素,它明确了以下有关 External Dependency 的关键概念。

Look at the second dependency element under dependencies in the above example, which clears the following key concepts about External Dependency.

  1. External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies.

  2. Specify groupId same as the name of the library.

  3. Specify artifactId same as the name of the library.

  4. Specify scope as system.

  5. Specify system path relative to the project location.

希望你现在已经对外部依赖项有了清晰的了解,你将能够在你的 Maven 项目中指定外部依赖项。

Hope now you are clear about external dependencies and you will be able to specify external dependencies in your Maven project.

Maven - Project Documents

本教程将教您如何一次性创建应用程序文档。因此,让我们开始,转到 C:/MVN 目录,您已使用前面的章节中给出的示例创建了您的 Java consumerBanking 应用程序。打开 consumerBanking 文件夹并执行以下 mvn 命令。

This tutorial will teach you how to create documentation of the application in one go. So let’s start, go to C:/MVN directory where you had created your java consumerBanking application using the examples given in the previous chapters. Open consumerBanking folder and execute the following mvn command.

如下所示,更新 C:\MVN\consumerBanking 文件夹中的 pom.xml。

Update, the pom.xml in C:\MVN\consumerBanking folder as shown below.

<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 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.bank</groupId>
   <artifactId>consumerBanking</artifactId>
   <packaging>jar</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>consumerBanking</name>
   <url>http://maven.apache.org</url>
   <properties>
      <maven.compiler.source>11</maven.compiler.source>
      <maven.compiler.target>11</maven.compiler.target>
   </properties>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.7</version>
         </plugin>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-project-info-reports-plugin</artifactId>
            <version>2.9</version>
         </plugin>
      </plugins>
   </build>
   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>
C:\MVN\consumerBanking>mvn site

Maven 将开始构建该项目。

Maven will start building the project.

[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< com.companyname.bank:consumerBanking >----------------
[INFO] Building consumerBanking 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-site-plugin:3.7:site (default-site) @ consumerBanking ---
[WARNING] Input file encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Relativizing decoration links with respect to localized project URL: http://maven.apache.org
[INFO] Rendering site with org.apache.maven.skins:maven-default-skin:jar:1.2 skin.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  5.850 s
[INFO] Finished at: 2021-12-13T17:49:56+05:30
[INFO] ------------------------------------------------------------------------

您的项目文档现已就绪。Maven 已在目标目录中创建了一个网站。

Your project documentation is now ready. Maven has created a site within the target directory.

site project structure

打开 C:\MVN\consumerBanking\target\site 文件夹。点击 index.html 可查看文档。

Open C:\MVN\consumerBanking\target\site folder. Click on index.html to see the documentation.

consumer web page

Maven 使用一个名为 Doxia 的文档处理引擎创建文档,该引擎可将多个源格式导入到公共文档模型中。要为您的项目编写文档,您可以在 Doxia 解析的以下几种常用格式中撰写您的内容。

Maven creates the documentation using a documentation-processing engine called Doxia which reads multiple source formats into a common document model. To write documentation for your project, you can write your content in a following few commonly used formats which are parsed by Doxia.

Format Name

Description

Reference

XDoc

A Maven 1.x documentation format

https://jakarta.apache.org/site

FML

Used for FAQ documents

https://maven.apache.org

Maven - Project Templates

Maven 使用 Archetype 的概念为用户提供了非常多的不同类型的项目模板列表(614 个)。Maven 帮助用户使用以下命令快速启动新的 Java 项目。

Maven provides users, a very large list of different types of project templates (614 in numbers) using the concept of Archetype. Maven helps users to quickly start a new java project using the following command.

mvn archetype:generate

What is Archetype?

Archetype 是一个 Maven 插件,其任务是根据其模板创建项目结构。我们将在本文中使用 quickstart archetype 插件来创建简单的 Java 应用程序。

Archetype is a Maven plugin whose task is to create a project structure as per its template. We are going to use quickstart archetype plugin to create a simple java application here.

Using Project Template

让我们打开命令控制台,转到 C:\ > MVN 目录,然后执行以下 mvn 命令。

Let’s open the command console, go to the C:\ > MVN directory and execute the following mvn command.

C:\MVN>mvn archetype:generate

Maven 将开始处理,并将要求选择所需的模版。

Maven will start processing and will ask to choose the required archetype.

C:\MVN>mvn archetype:generate
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
1: remote -> am.ik.archetype:elm-spring-boot-blank-archetype (Blank multi project for Spring Boot + Elm)
2: remote -> am.ik.archetype:graalvm-blank-archetype (Blank project for GraalVM)
...
3021: remote -> za.co.absa.hyperdrive:component-archetype_2.12 (-)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1843:

按 Enter 键选择默认选项 (1843: maven-archetype-quickstart)

Press Enter to choose to default option (1843: maven-archetype-quickstart)

Maven 将询问模版特定版本。

Maven will ask for particular version of archetype.

Choose org.apache.maven.archetypes:maven-archetype-quickstart version:
1: 1.0-alpha-1
2: 1.0-alpha-2
3: 1.0-alpha-3
4: 1.0-alpha-4
5: 1.0
6: 1.1
7: 1.3
8: 1.4
Choose a number: 8:

按 Enter 键选择默认选项 (8: maven-archetype-quickstart:1.4)

Press Enter to choose to default option (8: maven-archetype-quickstart:1.4)

Maven 将询问项目详细信息。按照要求输入项目详细信息。如果提供了默认值,请按 Enter 键。你可以通过输入自己的值来覆盖它们。

Maven will ask for the project detail. Enter project detail as asked. Press Enter if the default value is provided. You can override them by entering your own value.

Define value for property 'groupId': : com.companyname.insurance
Define value for property 'artifactId': : health
Define value for property 'version': 1.0-SNAPSHOT:
Define value for property 'package': com.companyname.insurance:

Maven 将询问项目详细信息确认。按 Enter 键或按 Y 键。

Maven will ask for the project detail confirmation. Press enter or press Y.

Confirm properties configuration:
groupId: com.companyname.insurance
artifactId: health
version: 1.0-SNAPSHOT
package: com.companyname.insurance
Y:

现在,Maven 将开始创建项目结构,并将显示以下内容:

Now Maven will start creating the project structure and will display the following −

[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.companyname.insurance
[INFO] Parameter: artifactId, Value: health
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: com.companyname.insurance
[INFO] Parameter: packageInPathFormat, Value: com/companyname/insurance
[INFO] Parameter: package, Value: com.companyname.insurance
[INFO] Parameter: groupId, Value: com.companyname.insurance
[INFO] Parameter: artifactId, Value: health
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Project created from Archetype in dir: C:\MVN\health
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  04:44 min
[INFO] Finished at: 2021-12-13T18:52:59+05:30
[INFO] ------------------------------------------------------------------------

Created Project

现在,转到 C:\ > MVN 目录。你将看到一个名为 health 的 Java 应用程序项目,即在创建项目时提供的 artifactId 。Maven 将为该项目创建如下所示的标准目录布局 −

Now go to C:\ > MVN directory. You’ll see a java application project created, named health, which was given as artifactId at the time of project creation. Maven will create a standard directory layout for the project as shown below −

template project structure

Created POM.xml

Maven 为该项目生成了一个 POM.xml 文件,如下所示 −

Maven generates a POM.xml file for the project as listed below −

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.insurance</groupId>
   <artifactId>health</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>health</name>
   <url>http://maven.apache.org</url>
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   <dependencies>
      <dependency>
      <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>

Created App.java

Maven 为该项目生成了一个示例 Java 源文件 App.java,如下所示 −

Maven generates sample java source file, App.java for the project as listed below −

位置: C:\ > MVN > health > src > main > java > com > companyname > insurance > App.java

Location: C:\ > MVN > health > src > main > java > com > companyname > insurance > App.java.

package com.companyname.insurance;

/**
   * Hello world!
   *
*/
public class App {
   public static void main( String[] args ) {
      System.out.println( "Hello World!" );
   }
}

Created AppTest.java

Maven 为该项目生成了一个示例 Java 源代码测试文件 AppTest.java,如下所示 −

Maven generates sample java source test file, AppTest.java for the project as listed below −

位置: C:\ > MVN > health > src > test > java > com > companyname > insurance > AppTest.java

Location: C:\ > MVN > health > src > test > java > com > companyname > insurance > AppTest.java.

package com.companyname.insurance;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
   * Unit test for simple App.
*/
public class AppTest extends TestCase {
   /**
      * Create the test case
      *
     * @param testName name of the test case
   */
   public AppTest( String testName ) {
      super( testName );
   }
   /**
      * @return the suite of tests being tested
   */
   public static Test suite() {
      return new TestSuite( AppTest.class );
   }
   /**
      * Rigourous Test :-)
   */
   public void testApp() {
      assertTrue( true );
   }
}

你现在可以看到 Maven 的强大功能。你可以在 maven 中使用单个命令创建任何类型的项目,并且立即启动你的开发。

Now you can see the power of Maven. You can create any kind of project using single command in maven and can kick-start your development.

Different Archetypes

Sr.No.

Archetype ArtifactIds & Description

1

maven-archetype-archetype An archetype, which contains a sample archetype.

2

maven-archetype-j2ee-simple An archetype, which contains a simplified sample J2EE application.

3

maven-archetype-mojo An archetype, which contains a sample a sample Maven plugin.

4

maven-archetype-plugin An archetype, which contains a sample Maven plugin.

5

maven-archetype-plugin-site An archetype, which contains a sample Maven plugin site.

6

maven-archetype-portlet An archetype, which contains a sample JSR-268 Portlet.

7

maven-archetype-quickstart An archetype, which contains a sample Maven project.

8

maven-archetype-simple An archetype, which contains a simple Maven project.

9

maven-archetype-site An archetype, which contains a sample Maven site to demonstrates some of the supported document types like APT, XDoc, and FML and demonstrates how to i18n your site.

10

maven-archetype-site-simple An archetype, which contains a sample Maven site.

11

maven-archetype-webapp An archetype, which contains a sample Maven Webapp project.

Maven - Snapshots

大型软件应用程序通常包含多个模块,在多个团队处理同一应用程序的不同模块时,这种情况很常见。例如,假设有一个团队正在处理应用程序的前端,作为 app-ui 项目(app-ui.jar:1.0),并且他们正在使用 data-service 项目(data-service.jar:1.0)。

A large software application generally consists of multiple modules and it is common scenario where multiple teams are working on different modules of same application. For example, consider a team is working on the front end of the application as app-ui project (app-ui.jar:1.0) and they are using data-service project (data-service.jar:1.0).

现在可能发生的情况是,负责 data-service 的团队正在快速修复 bug 或进行增强,他们几乎每隔一天就会向远程存储库发布库。

Now it may happen that team working on data-service is undergoing bug fixing or enhancements at rapid pace and they are releasing the library to remote repository almost every other day.

现在,如果 data-service 团队每隔一天上传一个新版本,那么将会出现以下问题 −

Now if data-service team uploads a new version every other day, then following problems will arise −

  1. data-service team should tell app-ui team every time when they have released an updated code.

  2. app-ui team required to update their pom.xml regularly to get the updated version.

为了处理此类情况, SNAPSHOT 的概念便应运而生。

To handle such kind of situation, SNAPSHOT concept comes into play.

What is SNAPSHOT?

SNAPSHOT 是一个特殊版本,它表示当前开发副本。与常规版本不同,Maven 会在远程存储库中为每次构建检查新的 SNAPSHOT 版本。

SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build.

现在,data-service 团队将每次向存储库发布更新的代码的 SNAPSHOT,比如 data-service:1.0-SNAPSHOT,替换旧的 SNAPSHOT jar。

Now data-service team will release SNAPSHOT of its updated code every time to repository, say data-service: 1.0-SNAPSHOT, replacing an older SNAPSHOT jar.

Snapshot vs Version

对于版本,如果 Maven 曾经下载过提到的版本,比如 data-service:1.0,它将永远不会尝试下载存储库中可用的较新的 1.0。要下载更新的代码,data-service 版本应升级到 1.1。

In case of Version, if Maven once downloaded the mentioned version, say data-service:1.0, it will never try to download a newer 1.0 available in repository. To download the updated code, data-service version is be upgraded to 1.1.

对于 SNAPSHOT,Maven 将每次 app-ui 团队构建其项目时自动获取最新的 SNAPSHOT(data-service:1.0-SNAPSHOT)。

In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT (data-service:1.0-SNAPSHOT) every time app-ui team build their project.

app-ui pom.xml

app-ui 项目使用 data-service 1.0-SNAPSHOT。

app-ui project is using 1.0-SNAPSHOT of data-service.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>app-ui</groupId>
   <artifactId>app-ui</artifactId>
   <version>1.0</version>
   <packaging>jar</packaging>
   <name>health</name>
   <url>http://maven.apache.org</url>
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   <dependencies>
      <dependency>
      <groupId>data-service</groupId>
         <artifactId>data-service</artifactId>
         <version>1.0-SNAPSHOT</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>

data-service pom.xml

data-service 项目对每一次轻微的变更发布1.0-SNAPSHOT。

data-service project is releasing 1.0-SNAPSHOT for every minor change.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>data-service</groupId>
   <artifactId>data-service</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>health</name>
   <url>http://maven.apache.org</url>
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
</project>

尽管对于 SNAPSHOT,Maven 会在每天自动提取最新的 SNAPSHOT,但你可以通过任何 Maven 命令使用 -U 转换强制 Maven 下载最新的快照构建。

Although, in case of SNAPSHOT, Maven automatically fetches the latest SNAPSHOT on daily basis, you can force maven to download latest snapshot build using -U switch to any maven command.

mvn clean package -U

让我们打开命令控制台,进入 C:\ > MVN > app-ui 目录并执行以下 mvn 命令。

Let’s open the command console, go to the C:\ > MVN > app-ui directory and execute the following mvn command.

C:\MVN\app-ui>mvn clean package -U

Maven 会在下载 data-service 的最新 SNAPSHOT 后开始构建项目。

Maven will start building the project after downloading the latest SNAPSHOT of data-service.

[INFO] Scanning for projects...
[INFO]--------------------------------------------
[INFO] Building consumerBanking
[INFO]    task-segment: [clean, package]
[INFO]--------------------------------------------
[INFO] Downloading data-service:1.0-SNAPSHOT
[INFO] 290K downloaded.
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting directory C:\MVN\app-ui\target
[INFO] [resources:resources {execution: default-resources}]

[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!

[INFO] skip non existing resourceDirectory C:\MVN\app-ui\src\main\resources
[INFO] [compiler:compile {execution:default-compile}]
[INFO] Compiling 1 source file to C:\MVN\app-ui\target\classes
[INFO] [resources:testResources {execution: default-testResources}]

[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!

[INFO] skip non existing resourceDirectory C:\MVN\app-ui\src\test\resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Compiling 1 source file to C:\MVN\app-ui\target\test-classes
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: C:\MVN\app-ui\target\
surefire-reports

--------------------------------------------------
 T E S T S
--------------------------------------------------

Running com.companyname.bank.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: C:\MVN\app-ui\target\
app-ui-1.0-SNAPSHOT.jar
[INFO]--------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO]--------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: 2015-09-27T12:30:02+05:30
[INFO] Final Memory: 16M/89M
[INFO]------------------------------------------------------------------------

Maven - Build Automation

构建自动化定义了依赖项目构建过程在项目构建成功完成后启动的方案,以确保依赖项目稳定。

Build Automation defines the scenario where dependent project(s) build process gets started once the project build is successfully completed, in order to ensure that dependent project(s) is/are stable.

Example

考虑一个团队正在开发一个项目 bus-core-api ,另两个项目 app-web-uiapp-desktop-ui 依赖于该项目。

Consider a team is developing a project bus-core-api on which two other projects app-web-ui and app-desktop-ui are dependent.

app-web-ui 项目正在使用 bus-core-api 项目的 1.0-SNAPSHOT。

app-web-ui project is using 1.0-SNAPSHOT of bus-core-api project.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>app-web-ui</groupId>
   <artifactId>app-web-ui</artifactId>
   <version>1.0</version>
   <packaging>jar</packaging>
   <dependencies>
      <dependency>
         <groupId>bus-core-api</groupId>
            <artifactId>bus-core-api</artifactId>
            <version>1.0-SNAPSHOT</version>
      </dependency>
   </dependencies>
</project>

app-desktop-ui 项目正在使用 bus-core-api 项目的 1.0-SNAPSHOT。

app-desktop-ui project is using 1.0-SNAPSHOT of bus-core-api project.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>app_desktop_ui</groupId>
   <artifactId>app_desktop_ui</artifactId>
   <version>1.0</version>
   <packaging>jar</packaging>
   <name>app_desktop_ui</name>
   <url>http://maven.apache.org</url>
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>bus_core_api</groupId>
         <artifactId>bus_core_api</artifactId>
         <version>1.0-SNAPSHOT</version>
         <scope>system</scope>
         <systemPath>C:\MVN\bus_core_api\target\bus_core_api-1.0-SNAPSHOT.jar</systemPath>
      </dependency>
   </dependencies>
</project>

bus-core-api 项目 -

bus-core-api project −

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>bus_core_api</groupId>
   <artifactId>bus_core_api</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>jar</packaging>
</project>

现在, app-web-uiapp-desktop-ui 项目的团队要求只要 bus-core-api 项目发生更改,就应启动他们的构建过程。

Now, teams of app-web-ui and app-desktop-ui projects require that their build process should kick off whenever bus-core-api project changes.

使用快照可确保使用最新的 bus-core-api 项目,但为了满足上述要求,我们需要做一些额外的事情。

Using snapshot, ensures that the latest bus-core-api project should be used but to meet the above requirement we need to do something extra.

我们可以采用以下两种方式进行:

We can proceed with the following two ways −

  1. Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds.

  2. Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically.

Using Maven

更新 bus-core-api 项目 pom.xml。

Update bus-core-api project pom.xml.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>bus-core-api</groupId>
   <artifactId>bus-core-api</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>jar</packaging>
   <build>
      <plugins>
         <plugin>
         <artifactId>maven-invoker-plugin</artifactId>
         <version>1.6</version>
         <configuration>
            <debug>true</debug>
            <pomIncludes>
               <pomInclude>app-web-ui/pom.xml</pomInclude>
               <pomInclude>app-desktop-ui/pom.xml</pomInclude>
            </pomIncludes>
         </configuration>
         <executions>
            <execution>
               <id>build</id>
               <goals>
                  <goal>run</goal>
               </goals>
            </execution>
         </executions>
         </plugin>
      </plugins>
   <build>
</project>

让我们打开命令控制台,转到 C:\ > MVN > bus-core-api 目录并执行以下 mvn 命令。

Let’s open the command console, go to the C:\ > MVN > bus-core-api directory and execute the following mvn command.

>mvn clean package -U

Maven 将开始构建 bus-core-api 项目。

Maven will start building the project bus-core-api.

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------
[INFO] Building bus-core-api
[INFO] task-segment: [clean, package]
[INFO] ------------------------------------------------------------------
...
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: C:\MVN\bus-core-ui\target\
bus-core-ui-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------

bus-core-api 构建成功后,Maven 将开始构建 app-web-ui 项目。

Once bus-core-api build is successful, Maven will start building the app-web-ui project.

[INFO] ------------------------------------------------------------------
[INFO] Building app-web-ui
[INFO] task-segment: [package]
[INFO] ------------------------------------------------------------------
...
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: C:\MVN\app-web-ui\target\
app-web-ui-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------

app-web-ui 构建成功后,Maven 将开始构建 app-desktop-ui 项目。

Once app-web-ui build is successful, Maven will start building the app-desktop-ui project.

[INFO] ------------------------------------------------------------------
[INFO] Building app-desktop-ui
[INFO] task-segment: [package]
[INFO] ------------------------------------------------------------------
...
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: C:\MVN\app-desktop-ui\target\
app-desktop-ui-1.0-SNAPSHOT.jar
[INFO] -------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------------

Using Continuous Integration Service with Maven

开发人员更倾向于使用 CI 服务器。每当添加一个新项目(例如 app-mobile-ui)时,都不需要更新 bus-core-api 项目,因为该项目是 bus-core-api 项目的依赖项目。Hudson 是一种用 Java 编写的持续集成工具,它包含在一个 servlet 容器中,例如 Apache tomcat 和 glassfish 应用服务器。Hudson 使用 Maven 依赖管理自动管理构建自动化。以下快照将定义 Hudson 工具的角色。

Using a CI Server is more preferable to developers. It is not required to update the bus-core-api project, every time a new project (for example, app-mobile-ui) is added, as dependent project on bus-core-api project. Hudsion is a continuous integration tool written in java, which in a servlet container, such as, Apache tomcat and glassfish application server. Hudson automatically manages build automation using Maven dependency management. The following snapshot will define the role of Hudson tool.

hudson maven job

Hudson 将每个项目构建视为作业。一旦将项目代码检入到 SVN(或映射到 Hudson 的任何源管理工具)中,Hudson 就会开始其构建作业,一旦此作业完成,它会自动开始其他依赖作业(其他依赖项目)。

Hudson considers each project build as job. Once a project code is checked-in to SVN (or any Source Management Tool mapped to Hudson), Hudson starts its build job and once this job gets completed, it start other dependent jobs (other dependent projects) automatically.

在上面的示例中,当 bus-core-ui 源代码在 SVN 中更新时,Hudson 就会开始其构建。构建成功后,Hudson 会自动查找依赖项目,并开始构建 app-web-uiapp-desktop-ui 项目。

In the above example, when bus-core-ui source code is updated in SVN, Hudson starts its build. Once build is successful, Hudson looks for dependent projects automatically, and starts building app-web-ui and app-desktop-ui projects.

Maven - Manage Dependencies

Maven 的核心功能之一是依赖项管理。一旦我们开始处理多模块项目(包含数百个模块/子项目),那么管理依赖项就会成为一项困难的任务。Maven 提供了高度的控制来管理此类场景。

One of the core features of Maven is Dependency Management. Managing dependencies is a difficult task once we’ve to deal with multi-module projects (consisting of hundreds of modules/sub-projects). Maven provides a high degree of control to manage such scenarios.

Transitive Dependencies Discovery

通常一种情况是,一个库(例如 A)依赖于另一个库(例如 B)。如果另一个项目 C 要使用 A,那么该项目需要使用库 B。

It is pretty often a case, when a library, say A, depends upon other library, say B. In case another project C wants to use A, then that project requires to use library B too.

Maven 帮助避免此类要求以发现所有必需的库。Maven 通过读取依赖项的项目文件 (pom.xml)、找出它们的依赖项等来做到这一点。

Maven helps to avoid such requirements to discover all the libraries required. Maven does so by reading project files (pom.xml) of dependencies, figure out their dependencies and so on.

我们只需要在每个项目 pom 中定义直接依赖。Maven 会自动处理其余部分。

We only need to define direct dependency in each project pom. Maven handles the rest automatically.

使用传递依赖项,包含的库的图形可能会迅速增长到很大程度。当出现重复库时,可能会出现这种情况。Maven 提供了一些功能来控制传递依赖项的范围。

With transitive dependencies, the graph of included libraries can quickly grow to a large extent. Cases can arise when there are duplicate libraries. Maven provides few features to control extent of transitive dependencies.

Sr.No.

Feature & Description

1

Dependency mediation Determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two dependency versions are at the same depth in the dependency tree, the first declared dependency will be used.

2

Dependency management Directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an example project C can include B as a dependency in its dependency Management section and directly control which version of B is to be used when it is ever referenced.

3

Dependency scope Includes dependencies as per the current stage of the build.

4

Excluded dependencies Any transitive dependency can be excluded using "exclusion" element. As example, A depends upon B and B depends upon C, then A can mark C as excluded.

5

Optional dependencies Any transitive dependency can be marked as optional using "optional" element. As example, A depends upon B and B depends upon C. Now B marked C as optional. Then A will not use C.

Dependency Scope

可以使用各种依赖项范围来限制传递依赖项发现,如下所述。

Transitive Dependencies Discovery can be restricted using various Dependency Scope as mentioned below.

Sr.No.

Scope & Description

1

compile This scope indicates that dependency is available in classpath of project. It is default scope.

2

provided This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime.

3

runtime This scope indicates that dependency is not required for compilation, but is required during execution.

4

test This scope indicates that the dependency is only available for the test compilation and execution phases.

5

system This scope indicates that you have to provide the system path.

6

import This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM’s <dependencyManagement> section.

Dependency Management

通常,在通用项目下,我们有一组项目。在这种情况下,我们可以创建一个具有所有通用依赖项的通用 pom,然后将此 pom 设为子项目 pom 的父级。下面的示例将帮助你理解此概念。

Usually, we have a set of project under a common project. In such case, we can create a common pom having all the common dependencies and then make this pom, the parent of sub-project’s poms. Following example will help you understand this concept.

dependency graph

以下是上述依赖项关系图的详细信息 -

Following are the detail of the above dependency graph −

  1. App-UI-WAR depends upon App-Core-lib and App-Data-lib.

  2. Root is parent of App-Core-lib and App-Data-lib.

  3. Root defines Lib1, lib2, Lib3 as dependencies in its dependency section.

App-UI-WAR

App-UI-WAR

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.groupname</groupId>
   <artifactId>App-UI-WAR</artifactId>
   <version>1.0</version>
   <packaging>war</packaging>
   <dependencies>
      <dependency>
         <groupId>com.companyname.groupname</groupId>
         <artifactId>App-Core-lib</artifactId>
         <version>1.0</version>
      </dependency>
   </dependencies>
   <dependencies>
      <dependency>
         <groupId>com.companyname.groupname</groupId>
         <artifactId>App-Data-lib</artifactId>
         <version>1.0</version>
      </dependency>
   </dependencies>
</project>

App-Core-lib

App-Core-lib

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
      <artifactId>Root</artifactId>
      <groupId>com.companyname.groupname</groupId>
      <version>1.0</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.groupname</groupId>
   <artifactId>App-Core-lib</artifactId>
   <version>1.0</version>
   <packaging>jar</packaging>
</project>

App-Data-lib

App-Data-lib

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
      <artifactId>Root</artifactId>
      <groupId>com.companyname.groupname</groupId>
      <version>1.0</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.groupname</groupId>
   <artifactId>App-Data-lib</artifactId>
   <version>1.0</version>
   <packaging>jar</packaging>
</project>

Root

Root

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.groupname</groupId>
   <artifactId>Root</artifactId>
   <version>1.0</version>
   <packaging>pom</packaging>
   <dependencies>
      <dependency>
         <groupId>com.companyname.groupname1</groupId>
         <artifactId>Lib1</artifactId>
         <version>1.0</version>
      </dependency>
   </dependencies>
   <dependencies>
      <dependency>
         <groupId>com.companyname.groupname2</groupId>
         <artifactId>Lib2</artifactId>
         <version>2.1</version>
      </dependency>
   </dependencies>
   <dependencies>
      <dependency>
         <groupId>com.companyname.groupname3</groupId>
         <artifactId>Lib3</artifactId>
         <version>1.1</version>
      </dependency>
   </dependencies>
</project>

现在,当我们构建 App-UI-WAR 项目时,Maven 将通过遍历依赖项关系图来发现所有依赖项,并构建应用程序。

Now when we build App-UI-WAR project, Maven will discover all the dependencies by traversing the dependency graph and build the application.

从以上示例中,我们可以了解以下关键概念 -

From above example, we can learn the following key concepts −

  1. Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM).

  2. There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail.

Maven - Deployment Automation

在项目开发中,一般情况下,部署流程包含以下步骤:

In project development, normally a deployment process consists of the following steps −

  1. Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it.

  2. Download the complete source code from SVN.

  3. Build the application.

  4. Store the build output either WAR or EAR file to a common network location.

  5. Get the file from network and deploy the file to the production site.

  6. Updated the documentation with date and updated version number of the application.

Problem Statement

一般情况下,上述部署流程涉及多人。一个团队可能处理代码检入,另一个团队可能处理构建,以此类推。很容易出现任何步骤因需要人工操作而遗漏,也可能是由于多团队环境所致。例如,可能未在网络计算机上替换旧的构建,而部署团队再次部署了旧构建。

There are normally multiple people involved in the above mentioned deployment process. One team may handle check-in of code, other may handle build and so on. It is very likely that any step may be missed out due to manual efforts involved and owing to multi-team environment. For example, older build may not be replaced on network machine and deployment team deployed the older build again.

Solution

通过结合以下内容来自动部署流程:

Automate the deployment process by combining the following −

  1. Maven, to build and release projects.

  2. SubVersion, source code repository, to manage source code.

  3. Remote Repository Manager (Jfrog/Nexus) to manage project binaries.

Update Project POM.xml

我们将使用 Maven Release 插件来创建一个自动化发布过程。

We will be using Maven Release plug-in to create an automated release process.

例如:bus-core-api 项目 POM.xml。

For Example: bus-core-api project POM.xml.

<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
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>bus-core-api</groupId>
   <artifactId>bus-core-api</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>jar</packaging>
   <scm>
      <url>http://www.svn.com</url>
      <connection>scm:svn:http://localhost:8080/svn/jrepo/trunk/
      Framework</connection>
      <developerConnection>scm:svn:${username}/${password}@localhost:8080:
      common_core_api:1101:code</developerConnection>
   </scm>
   <distributionManagement>
      <repository>
         <id>Core-API-Java-Release</id>
         <name>Release repository</name>
         <url>http://localhost:8081/nexus/content/repositories/
         Core-Api-Release</url>
      </repository>
   </distributionManagement>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-release-plugin</artifactId>
            <version>2.0-beta-9</version>
            <configuration>
               <useReleaseProfile>false</useReleaseProfile>
               <goals>deploy</goals>
               <scmCommentPrefix>[bus-core-api-release-checkin]-<
               /scmCommentPrefix>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

在 Pom.xml 中,我们使用了以下重要的元素:

In Pom.xml, following are the important elements we have used −

Sr.No.

Element & Description

1

SCM Configures the SVN location from where Maven will check out the source code.

2

Repositories Location where built WAR/EAR/JAR or any other artifact will be stored after code build is successful.

3

Plugin maven-release-plugin is configured to automate the deployment process.

Maven Release Plug-in

Maven 使用 maven-release-plugin 执行以下有用的任务。

The Maven does the following useful tasks using maven-release-plugin.

mvn release:clean

如果上次发布过程未成功,则清除工作空间。

It cleans the workspace in case the last release process was not successful.

mvn release:rollback

如果上次发布过程未成功,则回滚对工作空间代码和配置所做的更改。

Rollback the changes done to workspace code and configuration in case the last release process was not successful.

mvn release:prepare

执行多个操作,例如:

Performs multiple number of operations, such as −

  1. Checks whether there are any uncommitted local changes or not.

  2. Ensures that there are no SNAPSHOT dependencies.

  3. Changes the version of the application and removes SNAPSHOT from the version to make release.

  4. Update pom files to SVN.

  5. Run test cases.

  6. Commit the modified POM files.

  7. Tag the code in subversion

  8. Increment the version number and append SNAPSHOT for future release.

  9. Commit the modified POM files to SVN.

mvn release:perform

使用先前定义的标记签出代码,并运行 Maven deply 目标,将 war 或构建的制品部署到存储库。

Checks out the code using the previously defined tag and run the Maven deploy goal, to deploy the war or built artifact to repository.

让我们打开命令控制台,转到 C:\ > MVN >bus-core-api 目录并执行以下 mvn 命令。

Let’s open the command console, go to the C:\ > MVN >bus-core-api directory and execute the following mvn command.

>mvn release:prepare

Maven 将开始构建项目。成功构建后,运行以下 mvn 命令。

Maven will start building the project. Once build is successful run the following mvn command.

>mvn release:perform

成功构建后,您可以在存储库中验证上传的 JAR 文件。

Once build is successful you can verify the uploaded JAR file in your repository.

Maven - Web Application

本部分介绍如何使用 Maven 管理基于 Web 的项目。您将在此了解如何创建/构建/部署和运行 Web 应用程序。

This chapter teaches you how to manage a web based project using Maven. Here you will learn how to create/build/deploy and run a web application.

Create Web Application

要创建简单的 Java Web 应用程序,我们将使用 maven-archetype-webapp 插件。因此,让我们打开命令控制台,转至 C:\MVN 目录并执行以下 mvn 命令。

To create a simple java web application, we will use maven-archetype-webapp plugin. So, let’s open the command console, go to the C:\MVN directory and execute the following mvn command.

C:\MVN>mvn archetype:generate
-DgroupId = com.companyname.automobile
-DartifactId = trucks
-DarchetypeArtifactId = maven-archetype-webapp
-DinteractiveMode = false

Maven 将开始处理并将创建完整的基于 Web 的 Java 应用程序项目结构,如下所示 -

Maven will start processing and will create the complete web based java application project structure as follows −

C:\MVN>mvn archetype:generate -DgroupId=com.companyname.automobile -DartifactId=trucks -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
...
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: package, Value: com.companyname.automobile
[INFO] Parameter: groupId, Value: com.companyname.automobile
[INFO] Parameter: artifactId, Value: trucks
[INFO] Parameter: packageName, Value: com.companyname.automobile
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\trucks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  10.381 s
[INFO] Finished at: 2021-12-13T19:00:13+05:30
[INFO] ------------------------------------------------------------------------
C:\MVN>

现在转至 C:/MVN 目录。您将看到已创建名为 trucks(在 artifactId 中指定)的 Java 应用程序项目,如以下快照中所示。基于 Web 的应用程序通常使用以下目录结构 -

Now go to C:/MVN directory. You’ll see a java application project created, named trucks (as specified in artifactId) as specified in the following snapshot. The following directory structure is generally used for web applications −

web project structure

Maven 使用标准目录布局。使用以上示例,我们可以理解以下关键概念 -

Maven uses a standard directory layout. Using the above example, we can understand the following key concepts −

Sr.No.

Folder Structure & Description

1

trucks contains src folder and pom.xml.

2

src/main/webapp contains index.jsp and WEB-INF folder.

3

src/main/webapp/WEB-INF contains web.xml

4

src/main/resources it contains images/properties files.

POM.xml

<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
   http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.automobile</groupId>
   <artifactId>trucks</artifactId>
   <packaging>war</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>trucks Maven Webapp</name>
   <url>http://maven.apache.org</url>
   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
       </dependency>
   </dependencies>
   <build>
      <finalName>trucks</finalName>
   </build>
</project>

如果您仔细观察,您会发现 Maven 还创建了一个示例 JSP 源文件。

If you observe, you will find that Maven also created a sample JSP Source file.

打开 C:\ > MVN > trucks > src > main > webapp > 文件夹查看 index.jsp 及其代码:

Open C:\ > MVN > trucks > src > main > webapp > folder to see index.jsp with the following code −

<html>
   <body>
      <h2>Hello World!</h2>
   </body>
</html>

Build Web Application

让我们打开命令控制台,转至 C:\MVN\trucks 目录并执行以下 mvn 命令。

Let’s open the command console, go to the C:\MVN\trucks directory and execute the following mvn command.

C:\MVN\trucks>mvn clean package

Maven 将开始构建该项目。

Maven will start building the project.

C:\MVN\trucks>mvn clean package
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------< com.companyname.automobile:trucks >------------------
[INFO] Building trucks Maven Webapp 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ trucks ---
[INFO] Deleting C:\MVN\trucks\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ trucks ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ trucks ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ trucks ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\trucks\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ trucks ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ trucks ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-war-plugin:2.2:war (default-war) @ trucks ---
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields (file:/C:/Users/intel/.m2/repository/com/thoughtworks/xstream/xstream/1.3.1/xstream-1.3.1.jar) to field java.util.Properties.defaults
WARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
[INFO] Packaging webapp
[INFO] Assembling webapp [trucks] in [C:\MVN\trucks\target\trucks]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\MVN\trucks\src\main\webapp]
[INFO] Webapp assembled in [50 msecs]
[INFO] Building war: C:\MVN\trucks\target\trucks.war
[INFO] WEB-INF\web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.494 s
[INFO] Finished at: 2021-12-13T19:02:15+05:30
[INFO] ------------------------------------------------------------------------
C:\MVN\trucks>

Deploy Web Application

现在将 trucks.war 复制在 C:\ > MVN > trucks > target > 文件夹中创建到您的 web 服务器 webapp 目录中并重启该 web 服务器。

Now copy the trucks.war created in C:\ > MVN > trucks > target > folder to your webserver webapp directory and restart the webserver.

Test Web Application

使用 URL 运行 web 应用程序: http://<server-name>:<port-number>/trucks/index.jsp

Run the web-application using URL: http://<server-name>:<port-number>/trucks/index.jsp.

验证输出。

Verify the output.

web page

Maven - Eclipse IDE

Eclipse 提供了一个出色的插件 m2eclipse ,该插件将 Maven 和 Eclipse 无缝集成在一起。

Eclipse provides an excellent plugin m2eclipse which seamlessly integrates Maven and Eclipse together.

m2eclipse 的一些功能如下所示:

Some of features of m2eclipse are listed below −

  1. You can run Maven goals from Eclipse.

  2. You can view the output of Maven commands inside the Eclipse, using its own console.

  3. You can update maven dependencies with IDE.

  4. You can Launch Maven builds from within Eclipse.

  5. It does the dependency management for Eclipse build path based on Maven’s pom.xml.

  6. It resolves Maven dependencies from the Eclipse workspace without installing to local Maven repository (requires dependency project be in same workspace).

  7. It automatic downloads the required dependencies and sources from the remote Maven repositories.

  8. It provides wizards for creating new Maven projects, pom.xml and to enable Maven support on existing projects

  9. It provides quick search for dependencies in remote Maven repositories.

Installing m2eclipse plugin

使用以下链接之一安装 m2eclipse:

Use one of the following links to install m2eclipse −

Eclipse

URL

Eclipse 3.5 (Gallileo)

Installing m2eclipse in Eclipse 3.5 (Gallileo)

Eclipse 3.6 (Helios)

Installing m2eclipse in Eclipse 3.6 (Helios)

以下示例将帮助您利用集成 Eclipse 和 maven 的好处。

Following example will help you to leverage benefits of integrating Eclipse and maven.

Import a maven project in Eclipse

  1. Open Eclipse.

  2. Select File > Import > option.

  3. Select Maven Projects Option. Click on Next Button.

import project
  1. Select Project location, where a project was created using Maven. We’ve created a Java Project consumer Banking in the previous chapters. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven.

  2. Click Finish Button.

import project2

现在,您可以在 eclipse 中看到 Maven 项目。

Now, you can see the maven project in eclipse.

eclipse project structure

现在,查看一下 consumer Banking 项目属性。您可以看到 Eclipse 已将 Maven 依赖项添加到 java 构建路径。

Now, have a look at consumer Banking project properties. You can see that Eclipse has added Maven dependencies to java build path.

java build path2

现在,是使用 eclipse 的 maven 能力构建这个项目的时候了。

Now, it is time to build this project using maven capability of eclipse.

  1. Right Click on consumerBanking project to open context menu.

  2. Select Run as option.

  3. Then maven package option.

Maven 将开始构建项目。您可以在 Eclipse 控制台中看到以下输出 −

Maven will start building the project. You can see the output in Eclipse Console as follows −

[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< com.companyname.bank:consumerBanking >----------------
[INFO] Building consumerBanking 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ consumerBanking ---
[INFO] Deleting C:\MVN\consumerBanking\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ consumerBanking ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ consumerBanking ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ consumerBanking ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ consumerBanking ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ consumerBanking ---
[INFO] Surefire report directory: C:\MVN\consumerBanking\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.companyname.bank.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ consumerBanking ---
[INFO] Building jar: C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.663 s
[INFO] Finished at: 2021-12-13T17:34:27+05:30
[INFO] ------------------------------------------------------------------------

现在,右键单击 App.java。选择 Run As 选项。然后选择 Java Application

Now, right click on App.java. Select Run As option. Then select Java Application.

run maven build

您将看到如下结果 −

You will see the result as follows −

Hello World!

Maven - NetBeans

NetBeans 6.7 及更高版本内置支持 Maven。在以前版本的案例中,Maven 插件可在插件管理器中找到。我们在本示例中使用的是 NetBeans 6.9。

NetBeans 6.7 and newer has in-built support for Maven. In case of previous version, Maven plugin is available in plugin Manager. We are using NetBeans 6.9 in this example.

以下是 NetBeans 的部分功能 −

Some of features of NetBeans are listed below −

  1. You can run Maven goals from NetBeans.

  2. You can view the output of Maven commands inside the NetBeans using its own console.

  3. You can update maven dependencies with IDE.

  4. You can Launch Maven builds from within NetBeans.

  5. NetBeans does the dependency management automatically based on Maven’s pom.xml.

  6. NetBeans resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace).

  7. NetBeans automatic downloads required dependencies and sources from the remote Maven repositories.

  8. NetBeans provides wizards for creating new Maven projects, pom.xml.

  9. NetBeans provides a Maven Repository browser that enables you to view your local repository and registered external Maven repositories.

以下示例将帮助您利用集成 NetBeans 和 Maven 的优势。

Following example will help you to leverage benefits of integrating NetBeans and Maven.

Open a maven project in NetBeans

  1. Open NetBeans.

  2. Select File Menu > Open Project option.

  3. Select Project location, where a project was created using Maven. We’ve created a Java Project consumerBanking. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven.

nb open project

现在,您可以在 NetBeans 中看到以下 Maven 项目。查看 consumerBanking 项目库和测试库。您会看到 NetBeans 已将 Maven 依赖项添加到其构建路径中。

Now, you can see the maven project in NetBeans. Have a look at consumerBanking project Libraries and Test Libraries. You can see that NetBeans has added Maven dependencies to its build path.

nb project structure

Build a maven project in NetBeans

现在是使用 NetBeans 的 Maven 功能构建此项目的时候了。

Now, Its time to build this project using maven capability of NetBeans.

  1. Right Click on consumerBanking project to open context menu.

  2. Select Clean and Build as option.

nb build options

Maven 将开始构建项目。您可以在 NetBeans 控制台中看到输出,如下所示:

Maven will start building the project. You can see the output in NetBeans Console as follows −

NetBeans: Executing 'mvn.bat -Dnetbeans.execution = true clean install'
NetBeans:      JAVA_HOME = C:\Program Files\Java\jdk1.6.0_21
Scanning for projects...
------------------------------------------------------------------------
Building consumerBanking
   task-segment: [clean, install]
------------------------------------------------------------------------
[clean:clean]
[resources:resources]
[WARNING] Using platform encoding (Cp1252 actually)
to copy filtered resources, i.e. build is platform dependent!
skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources
[compiler:compile]
Compiling 2 source files to C:\MVN\consumerBanking\target\classes
[resources:testResources]
[WARNING] Using platform encoding (Cp1252 actually)
to copy filtered resources, i.e. build is platform dependent!
skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources
[compiler:testCompile]
Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes
[surefire:test]
Surefire report directory: C:\MVN\consumerBanking\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.companyname.bank.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[jar:jar]
Building jar: C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar
[install:install]
Installing C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar
to C:\Users\GB3824\.m2\repository\com\companyname\bank\consumerBanking\
1.0-SNAPSHOT\consumerBanking-1.0-SNAPSHOT.jar
------------------------------------------------------------------------
BUILD SUCCESSFUL
------------------------------------------------------------------------
Total time: 9 seconds
Finished at: Thu Jul 19 12:57:28 IST 2012
Final Memory: 16M/85M
------------------------------------------------------------------------

Run Application in NetBeans

现在,右键单击 App.java。选择 Run File 作为选项。您将在 NetBeans 控制台中看到结果。

Now, right click on App.java. Select Run File as option. You will see the result in the NetBeans Console.

NetBeans: Executing 'mvn.bat -Dexec.classpathScope = runtime
-Dexec.args = -classpath %classpath com.companyname.bank.App
-Dexec.executable = C:\Program Files\Java\jdk1.6.0_21\bin\java.exe
-Dnetbeans.execution = true process-classes
org.codehaus.mojo:exec-maven-plugin:1.1.1:exec'
NetBeans:      JAVA_HOME = C:\Program Files\Java\jdk1.6.0_21
Scanning for projects...
------------------------------------------------------------------------
Building consumerBanking
   task-segment: [process-classes,
   org.codehaus.mojo:exec-maven-plugin:1.1.1:exec]
------------------------------------------------------------------------
[resources:resources]
[WARNING] Using platform encoding (Cp1252 actually)
to copy filtered resources, i.e. build is platform dependent!
skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources
[compiler:compile]
Nothing to compile - all classes are up to date
[exec:exec]
Hello World!
------------------------------------------------------------------------
BUILD SUCCESSFUL
------------------------------------------------------------------------
Total time: 1 second
Finished at: Thu Jul 19 14:18:13 IST 2012
Final Memory: 7M/64M
------------------------------------------------------------------------

Maven - IntelliJ IDEA IDE Integration

IntelliJ IDEA 内置了对 Maven 的支持。在本示例中,我们使用 IntelliJ IDEA Community Edition 11.1。

IntelliJ IDEA has in-built support for Maven. We are using IntelliJ IDEA Community Edition 11.1 in this example.

IntelliJ IDEA 的一些功能列在下面:

Some of the features of IntelliJ IDEA are listed below −

  1. You can run Maven goals from IntelliJ IDEA.

  2. You can view the output of Maven commands inside the IntelliJ IDEA using its own console.

  3. You can update maven dependencies within IDE.

  4. You can Launch Maven builds from within IntelliJ IDEA.

  5. IntelliJ IDEA does the dependency management automatically based on Maven’s pom.xml.

  6. IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace).

  7. IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories.

  8. IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml.

以下示例将帮助您充分利用将 IntelliJ IDEA 和 Maven 集成的优势。

Following example will help you to leverage benefits of integrating IntelliJ IDEA and Maven.

Create a new project in IntelliJ IDEA

我们将使用 New Project Wizard 导入 Maven 项目。

We will import Maven project using New Project Wizard.

  1. Open IntelliJ IDEA.

  2. Select File Menu > New Project Option.

  3. Select import project from existing model.

ij new project step1
  1. Select Maven option

ij new project step2
  1. Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven.

ij new project step3
  1. Select Maven project to import.

ij new project step4
  1. Enter name of the project and click finish.

ij new project step5
  1. Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section.

ij project structure

Build a maven project in IntelliJ IDEA

现在,是时候使用 IntelliJ IDEA 的功能来构建此项目了。

Now, it is time to build this project using capability of IntelliJ IDEA.

  1. Select consumerBanking project.

  2. Select Buid menu > Rebuild Project Option

你可以在 IntelliJ IDEA 控制台中看到输出

You can see the output in IntelliJ IDEA Console

4:01:56 PM Compilation completed successfully

Run Application in IntelliJ IDEA

  1. Select consumerBanking project.

  2. Right click on App.java to open context menu.

  3. select Run App.main()

ij run app

你将在 IntelliJ IDEA 控制台中看到结果。

You will see the result in IntelliJ IDEA Console.

"C:\Program Files\Java\jdk1.6.0_21\bin\java"
-Didea.launcher.port=7533
"-Didea.launcher.bin.path=
C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 11.1.2\bin"
-Dfile.encoding=UTF-8
-classpath "C:\Program Files\Java\jdk1.6.0_21\jre\lib\charsets.jar;

C:\Program Files\Java\jdk1.6.0_21\jre\lib\deploy.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\javaws.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\jce.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\jsse.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\management-agent.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\plugin.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\resources.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\rt.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\dnsns.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\localedata.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunjce_provider.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunmscapi.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunpkcs11.jar

C:\MVN\consumerBanking\target\classes;
C:\Program Files\JetBrains\
IntelliJ IDEA Community Edition 11.1.2\lib\idea_rt.jar"
com.intellij.rt.execution.application.AppMain com.companyname.bank.App
Hello World!

Process finished with exit code 0