Maven 笔记

本文档详尽介绍了Maven的基础知识,包括使用archetype创建项目、Maven坐标、依赖范围和分析,以及仓库配置,如远程仓库认证和部署。深入讨论了生命周期与插件的绑定、配置以及插件仓库的设定。同时,讲解了聚合和继承的概念,以及版本管理和灵活构建,如属性、Profile和资源过滤。最后,阐述了POM元素的详细解析,涵盖了Artifact、Project、Dependency和仓库等相关配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Maven 学习笔记

1      Maven基础介绍

1.1     使用archetype生成项目

archetype:['ɑrkə'taɪp]原型

如果要快速生成原型,可以使用archetype生成项目。

mvn archetype:generate

1.2    maven坐标

Manven坐标包括:groupID,artifactId,version,packing,classifier

参考Artifact

1.3     依赖的范围

scope:依赖的范围

        compile     :编译依赖范围。默认。编译、测试、运行都有效。

        test            : 测试依赖范围。测试时有效。

        provided   : 已提供依赖范围。编译、测试时有效。

        runtime      : 运行时依赖。测试、运行有效。

        system      : 系统依赖范围,同provided。配合systemPath使用,显示依赖文件的路径,不使用仓库,

而用本地绑定,不可移植。

                   import       :导入依赖范围。

           

1.4     依赖的分析

dependency:list / tree   可以查看依赖的信息

dependency:analyze     分析当前的依赖

 

2      Maven仓库的配置

 

2.1     仓库

仓库可以分为远程仓库,本地仓库。默认配置的情况下,当本地仓库没有构件的时候,就会尝试从中央仓库下载。(中央仓库是maven自带的远程仓库)。

私服是另外一种远程仓库,为了节省带宽和时间,局域网架设一个私服。用其代理外部的远程仓库。

除了中央仓库和私服,还有许多其他的公开的远程仓库。

 

                   修改maven仓库目录

                   修改maven安装目录/conf/settings.xml

                   <settings>

                            <localRepository>d:\myData\</ localRepository >

                   </…>

 

            远程仓库的配置:参考repositories

                  

其中releasessnapshots元素用来控制对于发布版和快照版的下载。

layout元素值default表示仓库的布局是Maven2Manven3的默认布局,而非Maven1的布局。

2.2     远程仓库的配置

2.2.1        远程仓库的认证

远程仓库如果需要配置,可以在settings.xml中配置认证信息。

假设需要为一个idmy-proj的仓库配置认证信息,编辑settings.xml如下:

<settings>

         <servers>

                   <server>

                            <id>my-proj</id>

                       <username>xxx</username>

<password>xxx</password>

                   </server>

         </servers>

</settings>

                   server元素的id必须与pom需要认证的repository元素的id完全一致。

2.2.2        部署至远程仓库

日常开发中可以将构建,发布到私服,或者远程仓库。Maven可以将构建发布到远程仓库。pom修改如下:

配置distributionManagement

  <distributionManagement>

    <snapshotRepository>

      <id>repo-id</id>

      <name>my snapshot repository</name>

      <url>file:///path/to/snapshot/repo</url>

    </snapshotRepository>

    <repository>

      <id>repo-id2</id>

      <name>my repository</name>

      <url>file:///path/to/repo</url>

    </repository>

  </distributionManagement>

包含repositorysnapshotRepository子元素,前者表示发布版本的仓库,后者表示快照的仓库。

往远程仓库部署构件的时候,往往需要认证,认证方式就是settings.xml创建一个元素。

配置成功后,可以使用mvn clean deploy发布。

2.3     镜像

如果仓库X可以提供Y的所有内容,那么可以认为XY的镜像。创建镜像的好处是,由于地理位置的因素,有些镜像比中央服务仓库的服务更快。配置如下

编辑settings.xml

<settings>

  ...

  <mirrors>

    <mirror>

      <id>maven.net.cn</id>

      <name>one of the central mirrors in china</name>

      <url>http://maven.net.cn/content/groups/public/</url>

      <mirrorOf>central</mirrorOf>

    </mirror>

  </mirrors>

  ...

</settings>

配置mirrorOf的值为central,表示该配置为中央仓库的配置。对于任何中央仓库的请求都会转至该镜像。

3       生命周期与插件

3.1     生命周期

Maven有三套独立的生命周期,cleandefaultsiteClean的生命周期的目的是清理项目,default的生命周期的目的是构建项目,site的目的是建立项目站点。

每个生命周期包含一些阶段,这些阶段是有序的。Clean的阶段有pre-cleancleanpost-clean。当用户执行post-clean时,前面两个自动执行.

3.1.1       Clean生命周期

Clean生命周期一共包含了三个阶段:

pre-clean  执行一些需要在clean之前完成的工作

clean  移除所有上一次构建生成的文件

post-clean  执行一些需要在clean之后立刻完成的工作

mvn clean 中的clean就是上面的clean,在一个生命周期中,运行某个阶段的时候,它之前的所有阶段都会被运行,也就是说,mvn clean等同于 mvn pre-clean clean ,如果我们运行 mvn post-clean,那么 pre-cleanclean都会被运行。这是Maven很重要的一个规则,可以大大简化命令行的输入。

3.1.2       default生命周期

Maven的最重要的Default生命周期,绝大部分工作都发生在这个生命周期中,这里,我只解释一些比较重要和常用的阶段:

·        validate

·        initialize

·        generate-sources

·        process-sources

·        generate-resources

·        process-resources     复制并处理资源文件,至目标目录,准备打包。

·        compile     编译项目的源代码。

·        process-classes

·        generate-test-sources

·        process-test-sources

·        generate-test-resources

·        process-test-resources     复制并处理资源文件,至目标测试目录。

·        test-compile     编译测试源代码。

·        process-test-classes

·        test     使用合适的单元测试框架运行测试。这些测试代码不会被打包或部署。

·        prepare-package

·        package     接受编译好的代码,打包成可发布的格式,如 JAR

·        pre-integration-test

·        integration-test

·        post-integration-test

·        verify

·        install     将包安装至本地仓库,以让其它项目依赖。

·        deploy     将最终的包复制到远程的仓库,以让其它开发人员与项目共享。

基本上,根据名称我们就能猜出每个阶段的用途,关于其它阶段的解释,请参考

记住,运行任何一个阶段的时候,它前面的所有阶段都会被运行,这也就是为什么我们运行mvn install的时候,代码会被编译,测试,打包。

3.1.3       default生命周期

Site生命周期的各个阶段:

·        pre-site     执行一些需要在生成站点文档之前完成的工作

·        site    生成项目的站点文档

·        post-site     执行一些需要在生成站点文档之后完成的工作,并且为部署做准备

·        site-deploy     将生成的站点文档部署到特定的服务器上

这里经常用到的是site阶段和site-deploy阶段,用以生成和发布Maven站点,这可是Maven相当强大的功能,Manager比较喜欢,文档及统计数据自动生成,很好看

3.2     插件目标

为了能够复用代码,往往能够完成多个任务,每个功能就是一个目标(goal)。比如dependency:analyzedependencytree。冒号前为插件前缀,冒号后面为插件的目标。

3.3     插件绑定

Maven的生命周期与插件相互绑定,完成实际的构建任务。生命周期的各个阶段与插件的目标相互绑定。例如编译这一任务,他对应了default生命周期的compile这一阶段,而maven-compiler-plugin这一插件的compile目标。

3.3.1        内置绑定

Maven为一些主要的生命周期阶段绑定了很多插件目标。比如:clean生命周期中的clean阶段,与maven-clean-pluginclean绑定。如下图

3.3.2        自定义绑定

将某个插件的目标绑定到生命周期的某个阶段。

假设把maven-source-plugin插件的jar-no-fork目标绑定到defaultverify阶段。(jar-no-fork主要用来创建项目的源码jar)

pom.xml的根元素下添加以下内容:

  <build>

         <plugins>

                   <plugin>

                            <groupId>org.apache.maven.plugins</groupId>

                            <artifactId>maven-source-plugin</artifactId>

                            <version>2.1.1</version>

                            <executions>

                                     <execution>

                                               <id>attach-sources</id>

                                               <phase>verify</phase>

                                               <goals>

                                                        <goal>jar-no-fork</goal>

                                               </goals>

                                     </execution>

                            </executions>

                   </plugin>

         </plugins>

   </build>

mvn clean install

从控制台输出可以看到在插件maven-jar-plugin插件执行jar目标后,紧接着执行verify阶段的jar-no-fork目标:

3.4     插件配置

完成了插件和生命周期的绑定之后,用户还可以配置插件目标的参数,调整插件目标所执行的任务。用户可以通过命令行和pom配置方式进行配置。

3.4.1        命令行插件配置

很多插件目标的参数都支持命令行配置,用户可以在命令行中使用-D参数,并伴随着一个参数键=参数值的形式。

Eg:maven-surefire-plugin提过了一个maven.test.skip参数,为true则跳过执行测试。

$  mvn install -Dmaven.test.skip=true

参数-Djava自带的,功能是通过命令行设置一个java系统属性,maven简单的重用了该参数。

3.4.2       POM中插件全局配置

用户可以在声明插件的时候,对插件进行一个全局的配置。不是所有参数都可以从命令行执行,有些参数在项目创建到项目发布也都不会改变,就可以在pom文件中一次性配置。比如java 1.5这个参数。

          <plugin>

              <groupId>org.apache.maven.plugins</groupId>

              <artifactId>maven-compiler-plugin</artifactId>

              <version>2.3.2</version>

              <configuration>

                  <source>1.6</source>

                  <target>1.6</target>

                  <encoding>UTF-8</encoding>

              </configuration>

           </plugin>

 

这样,不管绑定到compile阶段,还是绑定到test阶段,都可以用到该配置,仅于java1.6进行编译

3.4.3       POM中插件任务配置

以下配置可以让Maven在绑定的阶段执行任务。也可以绑定多个execetuion,让Maven在不同的生命周期执行不同的任务。
下例为ant脚本插件,用于执行ant命令,输出正在创建的目录,用于提示信息

<build>

         <plugins>

                   <plugin>

                   <groupId>org.apache.maven.plugins</groupId>

                   <artifactId>maven-antrun-plugin</artifactId>

                   <version>1.3</version>

                   <executions>

                            <execution>

                                     <id>ant-validate</id>

                                     <phase>validate</phase>

                                     <goals>

                                               <goal>run</goal>

                                     </goals>

                                     <configuration>

                                               <tasks>

                                                        <echo>I'm bound to validate phase.</echo>

                                               </tasks>

                                     </configuration>

                            </execution>

                            <execution>

                                     <id>ant-verify</id>

                                     <phase>verify</phase>

                                     <goals>

                                               <goal>run</goal>

                                     </goals>

                                     <configuration>

                                               <tasks>

                                                        <echo>I'm bound to verify phase.</echo>

                                               </tasks>

                                     </configuration>

                            </execution>

                   </executions>

                   </plugin>

         </plugins>

</build>

在上述代码中,首先,mvaen-antrun-plugin:runvalidate阶段绑定,从而构成一个idant-validate的任务。插件全局配置中的configuration元素位于plugin元素下面,而这里的configuration元素则位于execution元素下面,表示这是特定任务的配置,而非插件整体的配置。这个ant-validate任务配置了一个echo Act任务,向命令行输出一段文字,表示该任务是绑定到validate阶段的。第二个任务的idant-varify,它绑定到了verify阶段,同样它也输出一段文字到命令行,告诉我们任务绑定到了verify阶段。

3.5     插件仓库

配置参考pluginRepositories,当Maven需要依赖插件时,如果不存在,则从远程仓库查找。

4       聚合与继承

4.1     聚合

为了能使一条命令构建多个模块,可以采用聚合。比如如下:

es/pom.xml 

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sishuok</groupId>

    <artifactId>es</artifactId>

    <packaging>pom</packaging>

    <version>1.0-SNAPSHOT</version>

    <name>es</name>

    <modules>

        <module>web</module>

     </modules>

es/parent/pom.xml

    <modelVersion>4.0.0</modelVersion>

    <artifactId>web</artifactId>

    <packaging>war</packaging>

    <version>1.0-SNAPSHOT</version>

首先注意packaging,值为POM,对于聚合模块来说,其打包方式packaging的值必须为pom,否则无法构建。

其次,元素modules是实现聚合的最核心的配置。用户可以通过在打包方式为pom的项目中声明任意数量的module元素来实现模块的聚合。这里每个module的值都是一个当前pom的相对目录。

为了方便构建项目,通常将聚合模块放在项目目录的最顶层,其他模块最为子目录。聚合模块仅仅是帮助聚合其他模块构建的工具,本身并无实质的内容。如图:

 

maven会首先解析聚合模块的pom,分析要构建的模块,并计算出一个反应堆构建顺序,然后根据顺序依次构建各个模块。

4.2     继承

如果构建的项目中存在大量的相同配置,那么可以将相同的配置放在父模块中,然后子模块继承他。

比如es/parent/pom.xml

    <parent>

        <artifactId>es</artifactId>

        <groupId>com.sishuok</groupId>

        <version>1.0-SNAPSHOT</version>

        <relativePath>../pom.xml</relativePath>

</parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>es-parent</artifactId>

    <packaging>pom</packaging>

    <version>1.0-SNAPSHOT</version>

<name>parent</name>

parent元素声明父模块,parent下的子元素指定了父元素的坐标,其中relativePath指定了父模块pom的位置。通常可以将共同的依赖配置提取到父模块中。

4.2.1        依赖管理

    <dependencyManagement>

<dependencies>

        <dependency>

            <groupId>junit</groupId>

            <artifactId>junit</artifactId>

            <version>${junit.version}</version>

            <scope>test</scope>

        </dependency>

</dependencies>

    </dependencyManagement>

maven中提过了dependencyManagement元素既能让子模块继承到父模块的依赖配置,又能保证子模块的灵活性。在dependencyManagement下的依赖声明不会引入实际的依赖,但它能够约束dependencies下的依赖的使用。通常在parent中配置dependencyManagement,子类继承之后,再次引入依赖时,不需要配置version

这种依赖似乎不能减少配置,单能够统一项目规范,降低依赖冲突,如果子模块不声明依赖的使用,即使父pomdependencyManagement声明了,也不会有实际的效果。

4.2.2        插件管理

 

<build>  

<pluginManagement> 

  <plugins>    

 <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-enforcer-plugin</artifactId>

                <version>1.0-beta-1</version>

                <executions>

                    <execution>

                        <id>enforce-versions</id>

                        <goals>

                            <goal>enforce</goal>

                        </goals>

                        <configuration>

                            <rules>

                                <requireJavaVersion>

                                    <version>${jdk.version}</version>

                                </requireJavaVersion>

                            </rules>

                        </configuration>

                    </execution>

                </executions>

            </plugin>

        </plugins>

    </build>

maven中提过了pluginManagement元素帮助管理插件,该元素的配置不会造成插件的调用行为,只有当pom中真正配置了,才会使用。

4.3     约定优于配置

maven提倡“约定优于配置”,这样可以大量减少配置文件。比如

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sishuok</groupId>

    <artifactId>es</artifactId>

<version>1.0-SNAPSHOT</version>

遵照Maven的约定,项目应该这样构建

源码目录:src/main/java/

编译输出目录:target/classes/

打包方式:war

包输出目录:target/

遵循约定会损失一定的灵活性,但却能减少配置。如果非要不遵循,比如源码目录改成src/java,而非src/main/java.可以采用如下配置:

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sishuok</groupId>

    <artifactId>es</artifactId>

<version>1.0-SNAPSHOT</version>

<build>

    <sourceDirectory>src/java</sourceDirectory>

</build>

4.3.1        超级POM

任何一个Maven项目都隐式的继承该POM。如下:

<project>

  <modelVersion>4.0.0</modelVersion>

  <repositories>

    <repository>

      <id>central</id>

      <name>Central Repository</name>

      <url>http://repo.maven.apache.org/maven2</url>

      <layout>default</layout>

      <snapshots>

        <enabled>false</enabled>

      </snapshots>

    </repository>

  </repositories>

 

  <pluginRepositories>

    <pluginRepository>

      <id>central</id>

      <name>Central Repository</name>

      <url>http://repo.maven.apache.org/maven2</url>

      <layout>default</layout>

      <snapshots>

        <enabled>false</enabled>

      </snapshots>

      <releases>

        <updatePolicy>never</updatePolicy>

      </releases>

    </pluginRepository>

  </pluginRepositories>

 

  <build>

    <directory>${project.basedir}/target</directory>

    <outputDirectory>${project.build.directory}/classes</outputDirectory>

    <finalName>${project.artifactId}-${project.version}</finalName>

    <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>

    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>

    <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>

    <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>

    <resources>

      <resource>

        <directory>${project.basedir}/src/main/resources</directory>

      </resource>

    </resources>

    <testResources>

      <testResource>

        <directory>${project.basedir}/src/test/resources</directory>

      </testResource>

    </testResources>

    <pluginManagement>

      <!-- NOTE: These plugins will be removed from future versions of the super POM -->

      <!-- They are kept for the moment as they are very unlikely to conflict with lifecycle mappings (MNG-4453) -->

      <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.1</version>

        </plugin>

        <plugin>

          <artifactId>maven-release-plugin</artifactId>

          <version>2.0</version>

        </plugin>

      </plugins>

    </pluginManagement>

  </build>

 

  <reporting>

    <outputDirectory>${project.build.directory}/site</outputDirectory>

  </reporting>

 

  <profiles>

    <!-- NOTE: The release profile will be removed from future versions of the super POM -->

    <profile>

      <id>release-profile</id>

 

      <activation>

        <property>

          <name>performRelease</name>

          <value>true</value>

        </property>

      </activation>

 

      <build>

        <plugins>

          <plugin>

            <inherited>true</inherited>

            <artifactId>maven-source-plugin</artifactId>

            <executions>

              <execution>

                <id>attach-sources</id>

                <goals>

                  <goal>jar</goal>

                </goals>

              </execution>

            </executions>

          </plugin>

          <plugin>

            <inherited>true</inherited>

            <artifactId>maven-javadoc-plugin</artifactId>

            <executions>

              <execution>

                <id>attach-javadocs</id>

                <goals>

                  <goal>jar</goal>

                </goals>

              </execution>

            </executions>

          </plugin>

          <plugin>

            <inherited>true</inherited>

            <artifactId>maven-deploy-plugin</artifactId>

            <configuration>

              <updateReleaseInfo>true</updateReleaseInfo>

            </configuration>

          </plugin>

        </plugins>

      </build>

    </profile>

  </profiles>

</project>

4.4     反应堆

在一个多模块的项目中,反应堆是指所有模块组成的一个构建结构。对于单模块的项目,反应堆就是本身,如果多模块,则包含了各模块之间继承与依赖的关系,从而能够自动计算出合理的构建顺序。

有些时候,如果想构建某个单独的模块,可以裁剪反应堆。可以输入mvn –h查看。

-am, -- also – make 同时构建所有模块的依赖模块

-amd, --also-make-dependents同时构建所列模块的模块

-pl ,--projects <arg> 构建指定模块,模块间用逗号分隔

-rf, -resume-from <arg> 从指定模块构建反应堆

 

比如有模块 xxx ,yyy

eg: 使用-amd可以构建依赖于所有模块的模块

         $ mvn clean install -pl xxx -amd

eg: 使用-rf可以在完整的反应堆构建顺序上指定从哪个模块开始构建

         $ mvn clean install -rf xxx

eg: -pl –am或者-pl –amd的基础上,还可以用-rf,以对反应堆再次裁剪

         $ mvn clean install -pl xxx -amd –rf yyy

 

在开发项目中,可以运用上述参数跳过无需构建的模块。

5       版本管理

5.1     基本概念

版本管理是指项目整体版本的演变过程管理,从1.0-snapshot1.0,再到1.1-snapshot。版本控制是指借助版本控制工具(svn/cvs),追踪代码的每一次变更。

通常Maven的版本号定义约定如下:

<主版本>.<次版本>.<增量版本> - <里程碑版本>

 

主干、标签、分支的定义

主干:项目开发代码的主体,是从项目开始到当前都处于活动的状态。从这里可以获取项目的最新代码,及所有的更新。

分支:从主干的某个点分离出来的代码拷贝,不影响主干的前提下,进行重大bug的修复,做一些实验性质的开发。如果达到了要求合并(merge)到主干。

标签:表示主干或者分支的某个点的状态。代表稳定状态。

如下图:

5.2     自动化版本发布

我们可以利用Maven-release-plugin插件来实现版本发布流程的自动化。Maven Release Plugin主要有三个目标:

release:prepare 准备版本发布,执行以下操作:

检查是否有未提交的更新。

检查项目是否有快照版本依赖。

更具用户的输入将快照版本升级为发布版。

POM中的SCM信息更改为标签地址。

基于修改后的POM执行Maven构建

提交POM更新。

为代码打标签。

提交POM更新。

releaserollback回退到releaseprepare所执行的操作。将POM回退至releaseprepare之前的状态。该步骤不会删除生成的标签。

Release perform执行版本发布。签出releaseprepare生成的标签中的源代码,并在此基础上执行mvn deploy命令打包并部署构建至仓库。

要发布版本,首先需要为其添加正确的版本控制系统信息,一般配置项目的SCM详细。

    <scm>

       <connection>scm:git:https://crawler4j.googlecode.com/git/</connection>

       <developerConnection>scm:git:https://crawler4j.googlecode.com/git/

</developerConnection>

       <url>https://crawler4j.googlecode.com/git/</url>

    </scm>

Connection:表示一个可读的scm地址。

developerConnection:表示一个可写的SCM地址。

Url表示可以在浏览器中访问的scm地址。

元素必须以scm开头,冒号后为版本控制的工具类型(svn/cvs/git)。该配置告诉 Maven当前代码主干的位置。而版本发布还要涉及标签操作。因此还需要Maven-release-plugin告诉标签的基础目录。

在执行releaseprepare之前还有两个注意点:一、系统必须要提供svn命令行工具,无法使用图形化工具,如TortoiseSvn;二、POM必须配置了可用的部署仓库,因为releaseperform会执行deploy操作将构建发布到仓库。

6       灵活的构建

6.1    Maven属性

Maven属性通过《properties》元素,用户可以自定义属性,然后pom的其他地方通过${属性名}来引用改属性。

6.1.1        内置属性

主要有两个常用的属性:${basedir}表示项目根目录,即包含pom.xml文件的目录、${version}表示项目的版本

6.1.2       pom属性

用户可以使用该属性引用Pom文件中对应的元素的值,
例如:
${project.artifactId}就对应了元素的值
${project.build.sourceDirectory}项目的主源代码目录,默认为src/main/java
${project.build.directory}
项目构建的输出目录,默认为target
${project.outputDirectory}
项目的主代码编译输出目录,默认为target/classess
${project.testOutputDirectory}
项目测试代码编译输出目录,默认为target/test-classes
${project.groupId}
项目的groupId
${project.artifactId}
项目的artifactId
${project.version}
项目的version${version}等价
${project.build.finalName}项目打包输出文件的名称,默认为${project.artifactId}-${project.version}

6.1.3        自定义属性

用户可以在pom的元素下自定义maven属性

6.1.4        Settings属性

pom属性同理,用户使用以settings.开头的属性引用settings.xml文件中的xml元素的值,如常用的${settings.localRepository}指向用户本地仓库的地址

6.1.5        java系统属性

所有java系统属性都可以使用Maven属性引用,例如${user.home}指向了用户目录

6.1.6        环境变量属性

 

所有环境变量都可以使用以env开头的maven属性引用

 

6.2     Maven Profile

Maven 引入profile能够在构建的时候修改pom的一个子集,或者添加额外的配置元素。可以更具不同的环境采用不同的profile.

    <profiles>

        <profile>

            <id>dev</id>

            <properties>

                <deploy.env>dev</deploy.env>

            </properties>

        </profile>

        <profile>

            <id>prd</id>

            <properties>

                <deploy.env>prd</deploy.env>

            </properties>

        </profile>

        <profile>

            <id>tra</id>

            <properties>

                <deploy.env>tra</deploy.env>

            </properties>

        </profile>

    </profiles>

 

上述dev表示开发环境,tra测试环境,prd正式环境。开发人员可以在使用mvn命令加上-Pdev激活dev profile,而测试人员可以使用-Ptest 激活test profile.

6.2.1        激活profile

Maven提供了多种方式激活profile

Ø  命令行激活

用户可以使用mvn命令行参数-P加上profileid来激活profile,多个id之间逗号分隔。eg mvn clean install –Pdev

 

Ø  settings文件激活

如果用户希望某个profile默认一直处于激活状态,可以在settings.xml中添加activeProfile元素。

 

Ø  系统属性激活

用户可以配置当某系统实现存在的时候,自动激活。eg:

      <profile>

            <id>dev</id>

<!--            <activation> -->

<!--                <activeByDefault>true</activeByDefault> -->

<!--            </activation> -->

            <properties>

                <deploy.env>dev</deploy.env>

            </properties>

        </profile>

    设置默认为dev

或者

            <activation>

                <property>

                    <name>test<name>

                    <value>x</value>

</property>

            </activation>

当某系统属性test存在,且值等于x时,激活profile

 

Ø  操作系统环境激活

profile还可以根据操作系统环境,差异写进profile,然后配置他们基于操作系统环境激活。eg:

           <activation>

                <os>

                    <name>Windows XP<name>

                    <family>Windows</family>

                    <arch>x86</arch>

                    <version>5.1.2600</version>

</os>

            </activation>

这里family的值包括WindowsUnixMac,其他属性可以查询系统属性获得。

 

Ø  文件存在与否激活

profile还可以根据文件是否存在激活。eg:

           <activation>

                <file>

                    <missing>xxx.properties</missing >

                    <exists> yyyy.properties </exists >

                </file>

            </activation>

 

Ø  默认否激活

<!--            <activation> -->

<!--                <activeByDefault>true</activeByDefault> -->

<!--            </activation> -->

6.2.2        profile种类

根据具体的需要,可以在以下位置声明profile

pom.xml:对当前项目有效。

用户settings.xml: 用户目录下.m2/settings.xml中的profile对该用户有效

全局settings.xml:Maven安装目录下的conf/settings.xml

6.3     资源过滤

pom定义了profile属性,默认只有在pom才能被解析,如果xxx.profiledb.name=${db.name}${db.name}定义在POM还是无法解析。因此,需要让Maven解析资源文件中的Maven属性。

资源文件的处理其实是maven-resources-plugin做的事情,默认将主目录文件复制到输出目录,此时只需要开启资源过滤即可。

Maven 默认的主资源目录和测试资源目录定义在超级POM中,为了开启过滤,只需要加一行filtering配置即可。

       <resources>

           <resource>

              <directory>src/main/resources</directory>

              <filtering>true</filtering>

           </resource>

           <resource>

              <directory>src/main/resources-${deploy.env}</directory>

              <filtering>true</filtering>

           </resource>

       </resources>

6.4     资源过滤

web进行打包是,web资源文件默认一般不会过滤,无法使用Maven属性。如果要使用pom中的profile属性,则需要配置maven-war-pluginweb资源目录进行过滤。eg

         <plugin>

              <groupId>org.apache.maven.plugins</groupId>

              <artifactId>maven-war-plugin</artifactId>

              <version>2.1.1</version>

<configuration>  

<webResources>

  <resources>

      <filtering>true</filtering>

       <directory>src/main/webapp</directory>

       <includes>

          <include>**/*.css</include>

<include>**/*.js</include>

       </includes>

</resource >    

</webResources >      <packagingExcludes>WEB-INF/web.xml</packagingExcludes>

              </configuration>

    </plugin>

7       生成项目站点

7.1     自定义站点

Maven生成站点非常灵活,除了通过插件自动生成为,用户可以自定义站点。自定义站点,用户必须创建一个名为site.xml的站点描述符文件,默认位于src/site目录下。

7.2     自定义页面

Maven支持自定义站点界面。支持的比较好的文档格式为APTFML.

APT(Almost Plain Text)是一种基于类似维基的文档格式。所有APT文档必须位于src/site/apt目录。

FML(FAQ Markup Language) 是一种用来创建FAQ页面的xml文档格式,文档需要放到src/site/fml目录。

一般站点的目录结构如下:

 

7.3     部署站点

Maven 支持多种协议部署站点,包括FTPSCPDAV.同时也支持生成到本地。

    <!-- 分发管理 -->

    <distributionManagement>

        <!-- mvn site:deploy部署的位置-->

        <site>

            <id>local</id>

            <name>filesystem</name>

            <!-- 修改到磁盘的相应位置 -->

            <url>file:D:\target\site</url>

        </site>

    </distributionManagement>

 

 

8      pom元素详解

 

8.1    Artifact

 说明

如果groupId, artifactId, version这三个元素定义了一个项目的基本坐标。

groupId:项目属于哪一个组

artifactid:定义了当前Maven项目在组中唯一的ID

version:为版本号,snapshot为快照,说明处于开发中,是不稳定的版本。

packaging:打包类型,默认为jar.可以指定 war,pom

classifier:该元素用来帮助定义构建输出的一些附属构建。classifier不是项目直接定义的,由附加的插件生成的。

 

 例如

    <groupId>edu.uci.ics</groupId>

    <artifactId>crawler4j</artifactId>

    <packaging>jar</packaging>

    <version>3.6-SNAPSHOT</version>

8.2    Project

 例如

<name>crawler4j</name>

    <description>Open Source Web Crawler for Java</description>

    <url>http://code.google.com/p/crawler4j/</url>

8.3    Parent

8.4    Properties

8.5    Modules

8.6    profiles

8.7    SCM

 说明

我们可以利用Maven-release-plugin插件来实现版本发布流程的自动化。Maven Release Plugin主要有三个目标:

release:prepare 准备版本发布,执行以下操作:

releaserollback回退到releaseprepare所执行的操作。将POM回退至releaseprepare之前的状态。该步骤不会删除生成的标签。

Release perform执行版本发布。签出releaseprepare生成的标签中的源代码,并在此基础上执行mvn deploy命令打包并部署构建至仓库。

要发布版本,首先需要为其添加正确的版本控制系统信息,一般配置项目的SCM详细。

 例如

    <scm>

       <connection>scm:git:https://crawler4j.googlecode.com/git/</connection>

       <developerConnection>scm:git:https://crawler4j.googlecode.com/git/

</developerConnection>

       <url>https://crawler4j.googlecode.com/git/</url>

    </scm>

8.8    build

    <developers>

       <developer>

           <name>YasserGanjisaffar</name>

           <email>{lastname}@gmail.com</email>

       </developer>

    </developers>

8.9    licenses

    <licenses>

       <license>

           <name>TheApache Software License, Version 2.0</name>

           <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>

           <distribution>repo</distribution>

       </license>

    </licenses>

8.10       developers

    <developers>

       <developer>

           <name>YasserGanjisaffar</name>

           <email>{lastname}@gmail.com</email>

       </developer>

    </developers>

8.11       dependencies

 说明

如果groupId, artifactId, version这三个元素定义了一个项目的基本坐标。

type:依赖类型,默认为jar.可以指定 war,pom

scope:依赖的范围

optional:标记依赖是否可选

exclusions:用来排除传递依赖

 

 例如

   <dependency>

            <groupId>org.eclipse.jetty</groupId>

            <artifactId>jetty-server</artifactId>

            <version>${jetty.version}</version>

            <scope>test</scope>

<type></type>

<optional></optional>

            <exclusions>

                <exclusion>

                    <artifactId>javax.servlet</artifactId>

                    <groupId>org.eclipse.jetty.orbit</groupId>

                </exclusion>

            </exclusions>

        </dependency>

8.12       repositories

 说明

 

    定义远程仓库

    <repositories>

        <repository>

            <id>apache-repo</id>

            <name>apache Repository</name>

            <url>

https://repository.apache.org/content/groups/public/

</url>

        </repository>

        <repository>

            <id>travis-ci-repo</id>

            <name>travis-ci Repository</name>

            <url>

http://maven.mirrors.travis-ci.org/nexus/content/repositories/central

</url>

        </repository>

   </repositories>

 

8.13       pluginRepositories

    <pluginRepositories>

        <pluginRepository>

            <id>maven2-repo</id>

            <name>maven2 Repository</name>

            <url>http://repo1.maven.org/maven2/</url>

        </pluginRepository>

        <pluginRepository>

            <id>Codehaus repository</id>

            <url>http://repository.codehaus.org/</url>

        </pluginRepository>

        <pluginRepository>

            <id>maven-db-plugin-repo</id>

            <name>mavendb plugin repository</name>

            <url>https://maven-db-plugin.googlecode.com/svn/maven/repo</url>

            <layout>default</layout>

        </pluginRepository>

</pluginRepositories>

8.14       ciManagement

 

    <!--持续集成信息 -->

    <ciManagement>

        <system>continuum</system>

        <url>https://travis-ci.org/zhangkaitao/es</url>

        <notifiers>

            <notifier>

                <type>mail</type>

                <sendOnError>true</sendOnError>

                <sendOnFailure>true</sendOnFailure>

                <sendOnSuccess>true</sendOnSuccess>

                <sendOnWarning>false</sendOnWarning>

                <configuration>

                    <address>zhangkaitao0503@gmail.com</address>

                </configuration>

            </notifier>

        </notifiers>

    </ciManagement>

8.15       Organization

8.16       Issue Management

    <!--问题反馈信息 -->

    <issueManagement>

        <system>Github</system>

        <url>https://github.com/zhangkaitao/es/issues</url>

</issueManagement>

8.17       dependencyManagement

 说明

maven中提过了dependencyManagement元素既能让子模块继承到父模块的依赖配置,又能保证子模块的灵活性。在dependencyManagement下的依赖声明不会引入实际的依赖,但它能够约束dependencies下的依赖的使用。通常在parent中配置dependencyManagement,子类继承之后,再次引入依赖时,不需要配置version

这种依赖似乎不能减少配置,单能够统一项目规范,降低依赖冲突,如果子模块不声明依赖的使用,即使父pomdependencyManagement声明了,也不会有实际的效果。

 例如

    <dependencyManagement>

<dependencies>

        <dependency>

            <groupId>junit</groupId>

            <artifactId>junit</artifactId>

            <version>${junit.version}</version>

            <scope>test</scope>

        </dependency>

</dependencies>

</dependencyManagement>

8.18       pluginManagement

 说明

maven中提过了pluginManagement元素帮助管理插件,该元素的配置不会造成插件的调用行为,只有当pom中真正配置了,才会使用。

 例如

 

<build>  

<pluginManagement> 

  <plugins>    

 <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-enforcer-plugin</artifactId>

                <version>1.0-beta-1</version>

                <executions>

                    <execution>

                        <id>enforce-versions</id>

                        <goals>

                            <goal>enforce</goal>

                        </goals>

                        <configuration>

                            <rules>

                                <requireJavaVersion>

                                    <version>${jdk.version}</version>

                                </requireJavaVersion>

                            </rules>

                        </configuration>

                    </execution>

                </executions>

            </plugin>

        </plugins>

    </build>

8.19       distributionManagement

参考:部署至远程仓库  

 <!--分发管理 -->

    <distributionManagement>

        <!--mvn site:deploy 部署的位置-->

        <site>

            <id>local</id>

            <name>filesystem</name>

            <!--修改到磁盘的相应位置 -->

            <url>file:D:\target\site</url>

        </site>

    </distributionManagement>

8.20       Continuous Integration

 

 

 

9   附录

9.1     附录A  pom元素参考

<project>                                                        POMxml根元素

<parent>                                                         声明继承

<modules>                                                      声明聚合

<groupId>                                                      坐标元素之一

<packaging>                                                   坐标元素之一,默认值jar

<name>                                                       名称

<description>                                                 描述

<licenses><license>                            许可证

<mailingLists><mailingList>                        邮件列表

<developers><developer>                          开发者

<contributors><contributor>                       贡献者

<issueManagement>                            问题追踪系统

<ciManagement>                                            持续集成系统

<scm>                                                              版本控制系统

<prerequisites><maven>                    要求Maven最低版本,默认值为2.0

<build><sourceDirectory>                           主源码目录

<build><scriptSourceDirectory>              脚本源码目录

<build><testSourceDirectory>           测试源码目录

<build><outputDirectory>                           主源码输出目录

<build><testOutputDirectory>           测试源码输出目录

<build><resources><resource>                  主资源目录

<build><testResources>                              测试资源目录

<build><finalName>                            输出主构件的名称

<build><directory>                                       输出目录

<build><filters><filter>                               通过properties文件定义资源过滤属性

<build><extensions><extension>              扩展Maven的核心

<build><pluginManagement>                      插件管理

<build><plugins><plugin>                          插件

<profiles><profile>                                       POM Profile

<distributionManagement>

<repository>                                                  发布版本部署仓库

<distributionManagement>

<snapshotRepository>                                 快照版本部署仓库

<repositories><repository>                        仓库

<pluginRepositories><pluginRepository>插件仓库

<dependencies><dependency>          依赖

<properties>                                                  Maven属性

<reporting><plugins>                                  报告插件

9.2     附录B  settings元素参考

9.3     附录常用插件列表

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值