Maven笔记

2021-05-28  本文已影响0人  Teddy_b

一、Maven使用

1.1 背景介绍

微服务开发过程中,为了避免为每一个微服务创建一个单独的项目,可以将和项目息息相关的微服务放在一个工程中,通过Maven的多模块来组织管理。假设有这么一个场景,有三个微服务,分别为apiorderprice,介绍如下:

1.2 Maven多模块

1.2.1 Maven的父模块

我们将上述背景中的三个微服务在一个项目内开发,因此首先我们创建一个Maven工程,其POM文件内容大致如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.istio.app</groupId>
    <artifactId>istio-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>istio-app</name>
    <packaging>pom</packaging>
    <description>Istio Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <modules>
        <module>app-api</module>
        <module>app-order</module>
        <module>app-price</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            ...
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            ...
        </plugins>
    </build>

</project>

上述的POM文件即为三个微服务的父POM文件,有几点值得注意的地方:

1.2.1 Maven的子模块

api这个微服务为例,它的POM文件如下面这样:

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <parent>
        <groupId>com.istio.app</groupId>
        <artifactId>istio-app</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../</relativePath> <!-- lookup parent from repository -->
    </parent>

    <artifactId>app-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>app-api</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        ...
    </dependencies>

    <build>
        <plugins>
            ...
        </plugins>
    </build>

</project>

这个子模块的POM文件中同样也有几点值得注意的:

1.3 Maven的标签

Maven的POM文件中有很多标签,下面列举下那些经常用但很容易混淆的标签

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

二、Maven原理

2.1 Maven的生命周期

Maven通过其生命周期来帮助我们管理项目,我们经常执行的mvn clean package命令,其实就是在调用maven的生命周期来帮助我们完成清理、打包等工作。Maven的声明周期包括三个:

每个生命周期又包含多个阶段,就好比一个接口(Interface)会包含多个方法(Method),每个生命周期包含的主要阶段列举如下:

关于maven的生命周期必须要明确的两点:

2.2 Maven的插件

基本上,我们了解了maven的生命周期后在日常开发中就可以正常使用maven来管理项目了。如果想要深究maven生命周期背后的原理,那就必须要了解maven的插件了。

我们在项目开发过程中肯定见过如下的POM文件内容:

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
</build>

想要理解上面的POM文件内容,也必须要了解maven的插件。

2.2.1 从Maven生命周期了解插件

我们再次回到mvn clean这个命令,现在我们已经知道这个命令其实就是调用maven的clean生命周期内的clean阶段,我们看一下这个命令的输出:

E:\project\spring\mavenbase>mvn clean
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building maven-base 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ maven-base ---
[INFO] Deleting E:\my-project\spring\mavenbase\target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.203 s
[INFO] Finished at: 2021-05-28T11:42:16+08:00
[INFO] Final Memory: 7M/245M
[INFO] ------------------------------------------------------------------------

注意这行输出maven-clean-plugin:2.5:clean,这行表达了三个重要信息:插件名称是maven-clean-plugin,插件版本号是2.5,插件的目标是clean。这里引入了一个新的名词插件的目标,插件与插件目标的关系,其实就相当于生命周期与阶段的关系,插件是一个统一的接口(Interface),而插件目标是接口中的方法(Method)。
这行输出说明mvn clean命令背后真正干活的是maven-clean-plugin这个插件的clean这个目标,通俗的可以理解为mvn clean调用的是maven-clean-plugin这个接口的clean方法。

像上面这种阶段与目标的调用关系,我们可以称为绑定,不同阶段所绑定的插件目标如下:

阶段 插件:目标
clean maven-clean-plugin:clean
process-resources maven-resources-plugin:resources
compile maven-compiler-plugin:compile
process-test-resources maven-resources-plugin:testResources
test-compile maven-compiler-plugin:testCompile
test maven-surefile-plugin:test
package maven-jar-plugin:jar
install maven-install-plugin:install
deploy maven-deploy-plugin:deploy

还有一个命令mvn help,我们通常用来查询帮助信息,其本质也是绑定到了一个插件目标上,对应的是maven-help-plugin:help

2.2.2 使用Maven插件

我们通过maven-help-plugin来详细了解一下maven官方实现的插件

mvn <groupId>:<artifactId>:<goal>

# 命令中使用的是这个插件的全称,其中包括groupId和artifactId
E:\project\spring\mavenbase>mvn org.apache.maven.plugins:maven-help-plugin:help
...
[INFO] --- maven-help-plugin:3.2.0:help (default-cli) @ maven-base 
...
# 这个插件有8个目标,仅列出部分
This plugin has 8 goals:

help:describe
  Displays a list of the attributes for a Maven Plugin and/or goals (aka Mojo -
  Maven plain Old Java Object).

help:effective-pom
  Displays the effective POM as an XML for this build, with the active profiles
  factored in, or a specified artifact. If verbose, a comment is added to each
  XML element describing the origin of the line.

help:help
  Display help information on maven-help-plugin.
  Call mvn help:help -Ddetail=true -Dgoal=<goal-name> to display parameter
  details.
# 使用上面的describe目标查看这个插件的详情
E:\project\spring\mavenbase>mvn org.apache.maven.plugins:maven-help-plugin:describe -Dplugin=org.apache.maven.plugins:maven-help-plugin
...
[INFO] org.apache.maven.plugins:maven-help-plugin:3.2.0

Name: Apache Maven Help Plugin
...
Group Id: org.apache.maven.plugins
Artifact Id: maven-help-plugin
Version: 3.2.0
# 可以看出`maven-help-plugin`的简称是help,
Goal Prefix: help
# 命令中使用的是插件的简称
E:\my-project\spring\mavenbase>mvn help:describe -Dplugin=clean
...
Name: Maven Clean Plugin
...
Group Id: org.apache.maven.plugins
Artifact Id: maven-clean-plugin
Version: 2.5
# 这个插件的简称确实是clean
Goal Prefix: clean
# 这个插件有两个目标
This plugin has 2 goals:

clean:clean
  Description: Goal which cleans the build.
    This attempts to clean a project's working directory of the files that were
    generated at build-time. By default, it discovers and deletes the
    directories configured in project.build.directory,
    project.build.outputDirectory, project.build.testOutputDirectory, and
    project.reporting.outputDirectory.

    Files outside the default may also be included in the deletion by
    configuring the filesets tag.

clean:help
  Description: Display help information on maven-clean-plugin.
    Call
     mvn clean:help -Ddetail=true -Dgoal=<goal-name>
    to display parameter details.

E:\project\spring\mavenbase>mvn help:describe -Dplugin=clean -Dgoal=clean -Ddetail
...
[INFO] Mojo: 'clean:clean'
clean:clean
  Description: ...
  # 这个目标开放了这些参数可设置,这也是我们在POM文件里通过<configuration>可以指定的参数来源
  Available parameters:

    excludeDefaultDirectories (Default: false)
      User property: clean.excludeDefaultDirectories
      ...

    failOnError (Default: true)
      User property: maven.clean.failOnError
      ...

    filesets
      The list of file sets to delete, in addition to the default directories.
      ...

    followSymLinks (Default: false)
      User property: clean.followSymLinks
      ...

    retryOnError (Default: true)
      User property: maven.clean.retryOnError
      ...

    skip (Default: false)
      User property: clean.skip
      ...

    verbose
      User property: clean.verbose
      ...

上面的目标详情里有两点值得注意:

看到这里后,读者应该明白了mvn clean package -DskipTests命令里的参数为什么能生效了。(可以自行验证猜想)

2.3 验证插件目标与生命周期阶段的绑定关系

前面我们直接给出了maven中的一些常见生命周期阶段与插件目标的绑定关系,下面我们通过查看父POM来验证下。(每个POM文件都会显示或隐式的继承自一个父POM,如果我们没有在项目POM文件中显示的声明<parent>标签,那么当前项目就隐式的继承自一个POM),我们看一下父POM的内容:

E:\project\spring\mavenbase>mvn help:effective-pom
...
[INFO] --- maven-help-plugin:3.2.0:effective-pom (default-cli) @ maven-base ---
[INFO]
Effective POMs, after inheritance, interpolation, and profiles are applied:

<?xml version="1.0" encoding="UTF-8"?>
<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Generated by Maven Help Plugin on 2021-05-28T16:06:20+08:00            -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/                -->
<!--                                                                        -->
<!-- ====================================================================== -->
<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Effective POM for project 'com.gjj.maven:maven-base:jar:1.0-SNAPSHOT'  -->
<!--                                                                        -->
<!-- ====================================================================== -->
<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.ap
ache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.gjj.maven</groupId>
  <artifactId>maven-base</artifactId>
  <version>1.0-SNAPSHOT</version>
  # 很多项目都会指定这个,经过今天的学习后,你应该能够知道这个为什么能够直接生效?
  # 提示:读者可以去看一下maven-resources-plugin这个插件的目标及参数详情
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  # maven默认从这里去拉取依赖
  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </repository>
  </repositories>
  # maven默认从这里去拉取插件
  <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>
    # maven默认的源代码、测试代码、编译代码的路径
    <sourceDirectory>E:\my-project\spring\mavenbase\src\main\java</sourceDirectory>
    <scriptSourceDirectory>E:\my-project\spring\mavenbase\src\main\scripts</scriptSourceDirectory>
    <testSourceDirectory>E:\my-project\spring\mavenbase\src\test\java</testSourceDirectory>
    <outputDirectory>E:\my-project\spring\mavenbase\target\classes</outputDirectory>
    <testOutputDirectory>E:\my-project\spring\mavenbase\target\test-classes</testOutputDirectory>
    <resources>
      <resource>
        <directory>E:\my-project\spring\mavenbase\src\main\resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>E:\my-project\spring\mavenbase\src\test\resources</directory>
      </testResource>
    </testResources>
    <directory>E:\my-project\spring\mavenbase\target</directory>
    <finalName>maven-base-1.0-SNAPSHOT</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.3.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
   # 以下即是插件目标与生命周期阶段的默认绑定关系
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.5</version>
        <executions>
          <execution>
            <id>default-clean</id>
            # maven-clean-plugin插件的goal=clean目标绑定到clean阶段
            <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>
            # maven-resources-plugin插件的goal=testResources目标绑定到process-test-resources阶段
            <phase>process-test-resources</phase>
            <goals>
              <goal>testResources</goal>
            </goals>
          </execution>
          <execution>
            <id>default-resources</id>
            # maven-resources-plugin插件的goal=resources目标绑定到process-resources阶段
            <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>
            # maven-jar-plugin插件的goal=jar目标绑定到package阶段
            <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>
            # maven-compiler-plugin插件的goal=compile目标绑定到compile阶段
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
          <execution>
            <id>default-testCompile</id>
            # maven-compiler-plugin插件的goal=testCompile目标绑定到test-compile阶段
            <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>E:\my-project\spring\mavenbase\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>E:\my-project\spring\mavenbase\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>E:\my-project\spring\mavenbase\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>E:\project\spring\mavenbase\target\site</outputDirectory>
  </reporting>
</project>

3. 前文遗留的两个问题

4. 参考

关于插件原理讲的很清楚:http://www.itsoku.com/article/240#menu_14
关于scope标签内容:https://blog.csdn.net/u010979642/article/details/107554068/

上一篇 下一篇

猜你喜欢

热点阅读