Maven——项目构建为王

                                                                           前言

     我的工具包在哪里,我的插件在哪里?哎,我的项目怎么缺了这个又缺了哪个,咦,这两个依赖版本不配合?不起效了!怎么办!怎么办!在Maven没有诞生前,这一系列的问题,总能困住一群又一群的开发人员,而今天的我们,因为有了maven,再也不必担心依赖于插件的问题啦。所以,我们有必要好好来了解一下Maven。

一、Maven简介

(一)什么是Maven

      Maven是apache下的开源项目,项目管理工具,管理java项目。

1、项目对象模型(Project Object Model)

      POM对象模型,每个maven工程中都有一个pom.xml文件,定义工程所依赖的jar包、本工程的座标、打包运行方式。。

2、依赖管理系统(基础核心 )

       maven通过座标对项目工程所依赖的jar包统一规范管理。

3、maven定义一套项目生命周期

清理、初始化、编译、测试、报告、打包、部署、站点生成

4、一组标准集合

       强调:maven工程有自己标准的工程目录结构、定义座标有标准。

5、maven 管理项目生命周期过程都是基于插件完成的

(二)Maven仓库

1、中央仓库

       就是远程仓库,仓库中jar由专业团队(maven团队)统一维护。

       中央仓库的地址:http://repo1.maven.org/maven2/

2、本地仓库

        相当于缓存,工程第一次会从远程仓库(互联网)去下载jar 包,将jar包存在本地仓库(在程序员的电脑上)。第二次不需要从远程仓库去下载。先从本地仓库找,如果找不到才会去远程仓库找。

3、私服

       在公司内部架设一台私服,其它公司架设一台仓库,对外公开。

二、Maven常用操作

Maven依赖查询
http://mvnrepository.com/

导入jar到本地仓库:

http://blog.csdn.net/we_shell/article/details/49819221

Maven常用命令
1. 创建Maven的普通java项目:
   mvn archetype:create
   -DgroupId=packageName
   -DartifactId=projectName 
2.
创建MavenWeb项目:  
    mvn archetype:create
    -DgroupId=packageName   
    -DartifactId=webappName
    -DarchetypeArtifactId=maven-archetype-webapp   
3.
编译源代码: mvn compile  (将项目中java文件编译为class,放在target目录)
4.
编译测试代码:mvn test-compile   
5.
运行测试:mvn test  
6.
产生sitemvn site  
7.
打包:mvn package      (先执行compile,然后将class文件打包成jar或war包到本项目target目录)
8. 在本地Repository中安装jarmvn install (先执行compile与package,然后将jar包安装到本地仓库) 
9.
清除产生的项目:mvn clean  
10.
生成eclipse项目:mvn eclipse:eclipse 
11.
生成idea项目:mvn idea:idea 
12.
组合使用goal命令,如只打包不测试:mvn -Dtest package  
13.
编译测试的内容:mvn test-compile 
14.
只打jar: mvn jar:jar 
15.
只测试而不编译,也不测试编译:mvn test -skipping compile -skipping test-compile
      ( -skipping
的灵活运用,当然也可以用于其他组合命令
16
只打包不测试:mvn package -Dmaven.test.skip=true -P prepare

17. 清除eclipse的一些系统设置:mvn eclipse:clean 

18.安装到远程仓库:mvn deploy

三、Maven的Setting.xml

顶级元素概览

下面列举了settings.xml中的顶级元素

<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 
     https://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository/>

  <interactiveMode/>

  <usePluginRegistry/>

  <offline/>

  <pluginGroups/>

  <servers/>

  <mirrors/>

  <proxies/>

  <profiles/>

  <activeProfiles/></settings>

LocalRepository

作用:该值表示构建系统本地仓库的路径
其默认值:~/.m2/repository。

<localRepository>${user.home}/.m2/repository</localRepository>

InteractiveMode

作用:表示maven是否需要和用户交互以获得输入。
如果maven需要和用户交互以获得输入,则设置成true,反之则应为false。默认为true。

<interactiveMode>true</interactiveMode>

UsePluginRegistry

作用:maven是否需要使用plugin-registry.xml文件来管理插件版本。
如果需要让maven使用文件~/.m2/plugin-registry.xml来管理插件版本,则设为true。默认为false。

<usePluginRegistry>false</usePluginRegistry>

Offline

作用:表示maven是否需要在离线模式下运行。
如果构建系统需要在离线模式下运行,则为true,默认为false。
当由于网络设置原因或者安全因素,构建服务器不能连接远程仓库的时候,该配置就十分有用。

<offline>false</offline>

PluginGroups

作用:当插件的组织id(groupId)没有显式提供时,供搜寻插件组织Id(groupId)的列表。
该元素包含一个pluginGroup元素列表,每个子元素包含了一个组织Id(groupId)。
当我们使用某个插件,并且没有在命令行为其提供组织Id(groupId)的时候,Maven就会使用该列表。默认情况下该列表包含了org.apache.maven.plugins和org.codehaus.mojo。

<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                     https://maven.apache.org/xsd/settings-1.0.0.xsd">

  ...

  <pluginGroups>

    <!--plugin的组织Id(groupId) -->
   <pluginGroup>org.codehaus.mojo</pluginGroup>

  </pluginGroups>

  ...</settings>

Servers

作用:一般,仓库的下载和部署是在pom.xml文件中的repositories和distributionManagement元素中定义的。然而,一般类似用户名、密码(有些仓库访问是需要安全认证的)等信息不应该在pom.xml文件中配置,这些信息可以配置在settings.xml中。

<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                     https://maven.apache.org/xsd/settings-1.0.0.xsd">

  ...

  <!--配置服务端的一些设置。一些设置如安全证书不应该和pom.xml一起分发。这种类型的信息应该存在于构建服务器上的settings.xml文件中。 -->

  <servers>

    <!--服务器元素包含配置服务器时需要的信息 -->

    <server>

      <!--这是server的id(注意不是用户登陆的id),该id与distributionManagement中repository元素的id相匹配。 -->

      <id>server001</id>

      <!--鉴权用户名。鉴权用户名和鉴权密码表示服务器认证所需要的登录名和密码。 -->

      <username>my_login</username>

      <!--鉴权密码。鉴权用户名和鉴权密码表示服务器认证所需要的登录名和密码。密码加密功能已被添加到2.1.0 +。详情请访问密码加密页面 -->

     <password>my_password</password>

      <!--鉴权时使用的私钥位置。和前两个元素类似,私钥位置和私钥密码指定了一个私钥的路径(默认是${user.home}/.ssh/id_dsa)以及如果需要的话,一个密语。将来passphrase和password元素可能会被提取到外部,但目前它们必须在settings.xml文件以纯文本的形式声明。 -->

     <privateKey>${usr.home}/.ssh/id_dsa</privateKey>

      <!--鉴权时使用的私钥密码。 -->

     <passphrase>some_passphrase</passphrase>

      <!--文件被创建时的权限。如果在部署的时候会创建一个仓库文件或者目录,这时候就可以使用权限(permission)。这两个元素合法的值是一个三位数字,其对应了unix文件系统的权限,如664,或者775。 -->

     <filePermissions>664</filePermissions>

      <!--目录被创建时的权限。 -->

     <directoryPermissions>775</directoryPermissions>

    </server>

  </servers>

  ...</settings>

Mirrors

作用:为仓库列表配置的下载镜像列表

<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                      https://maven.apache.org/xsd/settings-1.0.0.xsd">

  ...

  <mirrors>

    <!-- 给定仓库的下载镜像。 -->

    <mirror>

      <!-- 该镜像的唯一标识符。id用来区分不同的mirror元素。 -->

      <id>planetmirror.com</id>

      <!-- 镜像名称 -->

      <name>PlanetMirrorAustralia</name>

      <!-- 该镜像的URL。构建系统会优先考虑使用该URL,而非使用默认的服务器URL。 -->

     <url>http://downloads.planetmirror.com/pub/maven2</url>

      <!-- 被镜像的服务器的id。例如,如果我们要设置了一个Maven中央仓库(http://repo.maven.apache.org/maven2/)的镜像,就需要将该元素设置成central。这必须和中央仓库的id central完全一致。 -->

      <mirrorOf>central</mirrorOf>

    </mirror>

  </mirrors>

  ...</settings>

Proxies

作用:用来配置不同的代理。

<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                     https://maven.apache.org/xsd/settings-1.0.0.xsd">

  ...

  <proxies>

    <!--代理元素包含配置代理时需要的信息 -->

    <proxy>

      <!--代理的唯一定义符,用来区分不同的代理元素。 -->

      <id>myproxy</id>

      <!--该代理是否是激活的那个。true则激活代理。当我们声明了一组代理,而某个时候只需要激活一个代理的时候,该元素就可以派上用处。 -->

      <active>true</active>

      <!--代理的协议。协议://主机名:端口,分隔成离散的元素以方便配置。 -->

      <protocol>http</protocol>

      <!--代理的主机名。协议://主机名:端口,分隔成离散的元素以方便配置。 -->

      <host>proxy.somewhere.com</host>

      <!--代理的端口。协议://主机名:端口,分隔成离散的元素以方便配置。 -->

      <port>8080</port>

      <!--代理的用户名,用户名和密码表示代理服务器认证的登录名和密码。 -->

     <username>proxyuser</username>

      <!--代理的密码,用户名和密码表示代理服务器认证的登录名和密码。 -->

     <password>somepassword</password>

      <!--不该被代理的主机名列表。该列表的分隔符由代理服务器指定;例子中使用了竖线分隔符,使用逗号分隔也很常见。 -->

     <nonProxyHosts>*.google.com|ibiblio.org</nonProxyHosts>

    </proxy>

  </proxies>

  ...</settings>

 

Profiles

作用:根据环境参数来调整构建配置的列表。
settings.xml中的profile元素是pom.xml中profile元素的裁剪版本。
它包含了id、activation、repositories、pluginRepositories和 properties元素。这里的profile元素只包含这五个子元素是因为这里只关心构建系统这个整体(这正是settings.xml文件的角色定位),而非单独的项目对象模型设置。如果一个settings.xml中的profile被激活,它的值会覆盖任何其它定义在pom.xml中带有相同id的profile。

<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                      https://maven.apache.org/xsd/settings-1.0.0.xsd">

 ...

 <profiles>

   <profile>

     <!-- profile的唯一标识 -->

     <id>test</id>

     <!-- 自动触发profile的条件逻辑 -->

     <activation />

     <!-- 扩展属性列表 -->

     <properties />

     <!-- 远程仓库列表 -->

     <repositories />

     <!-- 插件仓库列表 -->

     <pluginRepositories />

   </profile>

 </profiles>

 ...</settings>

 

Activation

 

作用:自动触发profile的条件逻辑。
如pom.xml中的profile一样,profile的作用在于它能够在某些特定的环境中自动使用某些特定的值;这些环境通过activation元素指定。
activation元素并不是激活profile的唯一方式。settings.xml文件中的activeProfile元素可以包含profile的id。profile也可以通过在命令行,使用-P标记和逗号分隔的列表来显式的激活(如,-P test)。

<activation>

  <!--profile默认是否激活的标识 -->

 <activeByDefault>false</activeByDefault>

  <!--当匹配的jdk被检测到,profile被激活。例如,1.4激活JDK1.4,1.4.0_2,而!1.4激活所有版本不是以1.4开头的JDK。 -->

  <jdk>1.5</jdk>

  <!--当匹配的操作系统属性被检测到,profile被激活。os元素可以定义一些操作系统相关的属性。 -->

  <os>

    <!--激活profile的操作系统的名字 -->

    <name>Windows XP</name>

    <!--激活profile的操作系统所属家族(如 'windows') -->

    <family>Windows</family>

    <!--激活profile的操作系统体系结构 -->

    <arch>x86</arch>

    <!--激活profile的操作系统版本 -->

    <version>5.1.2600</version>

  </os>

  <!--如果Maven检测到某一个属性(其值可以在POM中通过${name}引用),其拥有对应的name = 值,Profile就会被激活。如果值字段是空的,那么存在属性名称字段就会激活profile,否则按区分大小写方式匹配属性值字段 -->

  <property>

    <!--激活profile的属性的名称 -->

    <name>mavenVersion</name>

    <!--激活profile的属性的值 -->

    <value>2.0.3</value>

  </property>

  <!--提供一个文件名,通过检测该文件的存在或不存在来激活profile。missing检查文件是否存在,如果不存在则激活profile。另一方面,exists则会检查文件是否存在,如果存在则激活profile。 -->

  <file>

    <!--如果指定的文件存在,则激活profile。 -->

   <exists>${basedir}/file2.properties</exists>

    <!--如果指定的文件不存在,则激活profile。 -->

   <missing>${basedir}/file1.properties</missing>

  </file></activation>

 

注:在maven工程的pom.xml所在目录下执行mvn help:active-profiles命令可以查看中央仓储的profile是否在工程中生效。

properties

作用:对应profile的扩展属性列表。
maven属性和ant中的属性一样,可以用来存放一些值。这些值可以在pom.xml中的任何地方使用标记${X}来使用,这里X是指属性的名称。属性有五种不同的形式,并且都能在settings.xml文件中访问。

<!--  1. env.X: 在一个变量前加上"env."的前缀,会返回一个shell环境变量。例如,"env.PATH"指代了$path环境变量(在Windows上是%PATH%)。   2. project.x:指代了POM中对应的元素值。例如: <project><version>1.0</version></project>通过${project.version}获得version的值。   3. settings.x: 指代了settings.xml中对应元素的值。例如:<settings><offline>false</offline></settings>通过 ${settings.offline}获得offline的值。   4. Java System Properties: 所有可通过java.lang.System.getProperties()访问的属性都能在POM中使用该形式访问,例如 ${java.home}。   5. x: 在<properties/>元素中,或者外部文件中设置,以${someVar}的形式使用。 --><properties>

 <user.install>${user.home}/our-project</user.install></properties>

注:如果该profile被激活,则可以在pom.xml中使用${user.install}。

Repositories

作用:远程仓库列表,它是maven用来填充构建系统本地仓库所使用的一组远程仓库。

<repositories>

  <!--包含需要连接到远程仓库的信息 -->

  <repository>

    <!--远程仓库唯一标识 -->

    <id>codehausSnapshots</id>

    <!--远程仓库名称 -->

    <name>Codehaus Snapshots</name>

    <!--如何处理远程仓库里发布版本的下载 -->

    <releases>

      <!--true或者false表示该仓库是否为下载某种类型构件(发布版,快照版)开启。 -->

      <enabled>false</enabled>

      <!--该元素指定更新发生的频率。Maven会比较本地POM和远程POM的时间戳。这里的选项是:always(一直),daily(默认,每日),interval:X(这里X是以分钟为单位的时间间隔),或者never(从不)。 -->

     <updatePolicy>always</updatePolicy>

      <!--当Maven验证构件校验文件失败时该怎么做-ignore(忽略),fail(失败),或者warn(警告)。 -->

     <checksumPolicy>warn</checksumPolicy>

    </releases>

    <!--如何处理远程仓库里快照版本的下载。有了releases和snapshots这两组配置,POM就可以在每个单独的仓库中,为每种类型的构件采取不同的策略。例如,可能有人会决定只为开发目的开启对快照版本下载的支持。参见repositories/repository/releases元素 -->

    <snapshots>

      <enabled />

      <updatePolicy />

      <checksumPolicy />

    </snapshots>

    <!--远程仓库URL,按protocol://hostname/path形式 -->

   <url>http://snapshots.maven.codehaus.org/maven2</url>

    <!--用于定位和排序构件的仓库布局类型-可以是default(默认)或者legacy(遗留)。Maven 2为其仓库提供了一个默认的布局;然而,Maven 1.x有一种不同的布局。我们可以使用该元素指定布局是default(默认)还是legacy(遗留)。 -->

    <layout>default</layout>

  </repository></repositories>

pluginRepositories

作用:发现插件的远程仓库列表。
和repository类似,只是repository是管理jar包依赖的仓库,pluginRepositories则是管理插件的仓库。
maven插件是一种特殊类型的构件。由于这个原因,插件仓库独立于其它仓库。pluginRepositories元素的结构和repositories元素的结构类似。每个pluginRepository元素指定一个Maven可以用来寻找新插件的远程地址。

<pluginRepositories>

  <!-- 包含需要连接到远程插件仓库的信息.参见profiles/profile/repositories/repository元素的说明 -->

  <pluginRepository>

    <releases>

      <enabled />

      <updatePolicy />

      <checksumPolicy />

    </releases>

    <snapshots>

      <enabled />

      <updatePolicy />

      <checksumPolicy />

    </snapshots>

    <id />

    <name />

    <url />

    <layout />

 </pluginRepository></pluginRepositories>

ActiveProfiles

作用:手动激活profiles的列表,按照profile被应用的顺序定义activeProfile。
该元素包含了一组activeProfile元素,每个activeProfile都含有一个profile id。任何在activeProfile中定义的profile id,不论环境设置如何,其对应的 profile都会被激活。如果没有匹配的profile,则什么都不会发生。
例如,env-test是一个activeProfile,则在pom.xml(或者profile.xml)中对应id的profile会被激活。如果运行过程中找不到这样一个profile,Maven则会像往常一样运行。

<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                     https://maven.apache.org/xsd/settings-1.0.0.xsd">

  ...

  <activeProfiles>

    <!-- 要激活的profile id -->

   <activeProfile>env-test</activeProfile>

  </activeProfiles>

  ...</settings>

四、Maven的Pom.xml

原文地址:http://blog.csdn.net/zhuxinhua/article/details/5788546

什么是pom?
    pom作为项目对象模型。通过xml表示maven项目,使用pom.xml来实现。主要描述了项目:包括配置文件;开发者需要遵循的规则,缺陷管理系统,组织和licenses,项目的url,项目的依赖性,以及其他所有的项目相关因素。

快速察看:

[html] view plain copy

  1. <project>  
  2.   <modelVersion>4.0.0</modelVersion>  
  3. <!--maven2.0必须是这样写,现在是maven2唯一支持的版本-->  
  4.   <!-- 基础设置 -->  
  5.   <groupId>...</groupId>  
  6.   <artifactId>...</artifactId>  
  7.   <version>...</version>  
  8.   <packaging>...</packaging>  
  9.   <name>...</name>  
  10.   <url>...</url>  
  11.   <dependencies>...</dependencies>  
  12.   <parent>...</parent>  
  13.   <dependencyManagement>...</dependencyManagement>  
  14.   <modules>...</modules>  
  15.   <properties>...</properties>  
  16.   
  17.   <!--构建设置 -->  
  18.   <build>...</build>  
  19.   <reporting>...</reporting>  
  20.   
  21.   <!-- 更多项目信息 -->  
  22.   <name>...</name>  
  23.   <description>...</description>  
  24.   <url>...</url>  
  25.   <inceptionYear>...</inceptionYear>  
  26.   <licenses>...</licenses>  
  27.   <organization>...</organization>  
  28.   <developers>...</developers>  
  29.   <contributors>...</contributors>  
  30.   
  31.   <!-- 环境设置-->  
  32.   <issueManagement>...</issueManagement>  
  33.   <ciManagement>...</ciManagement>  
  34.   <mailingLists>...</mailingLists>   
  35.   <scm>...</scm>  
  36.   <prerequisites>...</prerequisites>  
  37.   <repositories>...</repositories>  
  38.   <pluginRepositories>...</pluginRepositories>  
  39.   <distributionManagement>...</distributionManagement>  
  40.   <profiles>...</profiles>  
  41. </project>  

基本内容:

POM包括了所有的项目信息

groupId:项目或者组织的唯一标志,并且配置时生成路径也是由此生成,如org.myproject.mojo生成的相对路径为:/org/myproject/mojo

artifactId:项目的通用名称

version:项目的版本

packaging:打包机制,如pom,jar,maven-plugin,ejb,war,ear,rar,par

name:用户描述项目的名称,无关紧要的东西,可选

url:应该是只是写明开发团队的网站,无关紧要,可选

classifer:分类

其中groupId,artifactId,version,packaging这四项组成了项目的唯一座标。一般情况下,前面三项就可以组成项目的唯一座标了。

 

POM关系:主要为依赖,继承,合成

依赖关系:

 

[html] view plain copy

  1. <dependencies>  
  2.     <dependency>  
  3.       <groupId>junit</groupId>  
  4.       <artifactId>junit</artifactId>  
  5.       <version>4.0</version>  
  6.       <type>jar</type>  
  7.       <scope>test</scope>  
  8.       <optional>true</optional>  
  9.     </dependency>  
  10.    
  11.     <dependency>  
  12.         <groupId>com.alibaba.china.shared</groupId>  
  13.         <artifactId>alibaba.apollo.webx</artifactId>  
  14.         <version>2.5.0</version>  
  15.         <exclusions>  
  16.           <exclusion>  
  17.             <artifactId>org.slf4j.slf4j-api</artifactId>  
  18.             <groupId>com.alibaba.external</groupId>  
  19.           </exclusion>  
  20.           ....  
  21.         </exclusions>  
  22. ......  
  23. </dependencies>  

其中groupId, artifactId, version这三个组合标示依赖的具体工程,而且这个依赖工程必需是maven中心包管理范围内的,如果碰上非开源包,maven支持不了这个包,那么则有三种方法处理:

1.本地安装这个插件install plugin

例如:mvn install:intall-file -Dfile=non-maven-proj.jar -DgroupId=som.group -DartifactId=non-maven-proj -Dversion=1

2.创建自己的repositories并且部署这个包,使用类似上面的deploy:deploy-file命令,

3.设置scope为system,并且指定系统路径。

 

dependency里属性介绍:

type:默认为jar类型,常用的类型有:jar,ejb-client,test-jar...,可设置plugins中的extensions值为true后再增加新的类型,

scope:是用来指定当前包的依赖范围,maven的依赖范围

optional:设置指依赖是否可选,默认为false,即子项目默认都继承,为true,则子项目必需显示的引入,与dependencyManagement里定义的依赖类似 。

exclusions:如果X需要A,A包含B依赖,那么X可以声明不要B依赖,只要在exclusions中声明exclusion.

exclusion:是将B从依赖树中删除,如上配置,alibaba.apollo.webx不想使用com.alibaba.external  ,但是alibaba.apollo.webx是集成了com.alibaba.external,r所以就需要排除掉.

 

如果一个工程是parent或者aggregation(即mutil-module的)的,那么必须在packing赋值为pom,child工程从parent继承的包括:dependencies,developers,contributors,plugin lists,reports lists,plugin execution with matching ids,plugin configuration

parent的使用方法如下:

 

[html] view plain copy

  1. <parent>   
  2.     <groupId>org.codehaus.mojo</groupId>   
  3.     <artifactId>my-parent</artifactId>   
  4.     <version>2.0</version>   
  5.     <relativePath>../my-parent</relativePath>   
  6. </parent>  

relativePath是可选的,maven会首先搜索这个地址,在搜索本地远程repositories之前.

dependencyManagement:是用于帮助管理chidren的dependencies的。例如如果parent使用dependencyManagement定义了一个dependencyon junit:junit4.0,那么它的children就可以只引用 groupId和artifactId,而version就可以通过parent来设置,这样的好处就是可以集中管理依赖的详情

 

modules:对于多模块的project,outer-module没有必需考虑inner-module的dependencies,当列出modules的时候,modules的顺序是不重要的,因为maven会自动根据依赖关系来拓扑排序,

modules例子如下 :

<module>my-project</module>

<module>other-project</module>

 

properties:是为pom定义一些常量,在pom中的其它地方可以直接引用。

定义方式如下:

 

[html] view plain copy

  1. <properties>  
  2.       <file.encoding>UTF-8</file_encoding>  
  3.       <Java.source.version>1.5</java_source_version>  
  4.       <java.target.version>1.5</java_target_version>  
  5. </properties>  

使用方式 如下 :

${file.encoding}

 

还可以使用project.xx引用pom里定义的其它属性:如$(project.version} 

 

build设置:

defaultGoal:默认的目标,必须跟命令行上的参数相同,如:jar:jar,或者与时期parse相同,例如install

directory:指定build target目标的目录,默认为$(basedir}/target,即项目根目录下的target

finalName:指定去掉后缀的工程名字,例如:默认为${artifactId}-${version}

filters:用于定义指定filter属性的位置,例如filter元素赋值filters/filter1.properties,那么这个文件里面就可以定义name=value对,这个name=value对的值就可以在工程pom中通过${name}引用,默认的filter目录是${basedir}/src/main/fiters/

resources:描述工程中资源的位置 

 

[html] view plain copy

  1. <resource>   
  2.         <targetPath>META-INF/plexus</targetPath>   
  3.         <filtering>false</filtering>   
  4.         <directory>${basedir}/src/main/plexus</directory>   
  5.         <includes>   
  6.           <include>configuration.xml</include>   
  7.         </includes>   
  8.         <excludes>   
  9.           <exclude>**/*.properties</exclude>   
  10.         </excludes>   
  11. </resource>  

targetPath:指定build资源到哪个目录,默认是base directory

filtering:指定是否将filter文件(即上面说的filters里定义的*.property文件)的变量值在这个resource文件有效,例如上面就指定那些变量值在configuration文件无效。

directory:指定属性文件的目录,build的过程需要找到它,并且将其放到targetPath下,默认的directory是${basedir}/src/main/resources

includes:指定包含文件的patterns,符合样式并且在directory目录下的文件将会包含进project的资源文件。

excludes:指定不包含在内的patterns,如果inclues与excludes有冲突,那么excludes胜利,那些符合冲突的样式的文件是不会包含进来的。

testResources:这个模块包含测试资源元素,其内容定义与resources类似,不同的一点是默认的测试资源路径是${basedir}/src/test/resources,测试资源是不部署的。

 

plugins配置:

 

[html] view plain copy

  1. <plugin>   
  2.         <groupId>org.apache.maven.plugins</groupId>   
  3.         <artifactId>maven-jar-plugin</artifactId>   
  4.         <version>2.0</version>   
  5.         <extensions>false</extensions>   
  6.         <inherited>true</inherited>   
  7.         <configuration>   
  8.           <classifier>test</classifier>   
  9.         </configuration>   
  10.         <dependencies>...</dependencies>   
  11.         <executions>...</executions>   
  12. </plugin>  

extensions:true or false, 决定是否要load这个plugin的extensions,默认为true.

inherited:是否让子pom继承,ture or false 默认为true.

configuration:通常用于私有不开源的plugin,不能够详细了解plugin的内部工作原理,但使plugin满足的properties

dependencies:与pom基础的dependencies的结构和功能都相同,只是plugin的dependencies用于plugin,而pom的denpendencies用于项目本身。在plugin的dependencies主要用于改变plugin原来的dependencies,例如排除一些用不到的dependency或者修改dependency的版本等,详细请看pom的denpendencies.

executions:plugin也有很多个目标,每个目标具有不同的配置,executions就是设定plugin的目标,

 

[html] view plain copy

  1. <execution>   
  2.             <id>echodir</id>   
  3.             <goals>   
  4.               <goal>run</goal>   
  5.             </goals>   
  6.             <phase>verify</phase>   
  7.             <inherited>false</inherited>   
  8.             <configuration>   
  9.               <tasks>   
  10.                 <echo>Build Dir: ${project.build.directory}</echo>   
  11.               </tasks>   
  12.             </configuration>   
  13. </execution>   

id:标识符

goals:里面列出一系列的goals元素,例如上面的run goal

phase:声明goals执行的时期,例如:verify

inherited:是否传递execution到子pom里。

configuration:设置execution下列表的goals的设置,而不是plugin所有的goals的设置

 

pluginManagement配置:

pluginManagement的作用类似于denpendencyManagement,只是denpendencyManagement是用于管理项目jar包依赖,pluginManagement是用于管理plugin。与pom build里的plugins区别是,这里的plugin是列出来,然后让子pom来决定是否引用。

例如:

 

[html] view plain copy

  1. <pluginManagement>   
  2.       <plugins>   
  3.         <plugin>   
  4.           <groupId>org.apache.maven.plugins</groupId>   
  5.           <artifactId>maven-jar-plugin</artifactId>   
  6.           <version>2.2</version>   
  7.           <executions>   
  8.             <execution>   
  9.               <id>pre-process-classes</id>   
  10.               <phase>compile</phase>   
  11.               <goals>   
  12.                 <goal>jar</goal>   
  13.               </goals>   
  14.               <configuration>   
  15.                 <classifier>pre-process</classifier>   
  16.               </configuration>   
  17.             </execution>   
  18.           </executions>   
  19.         </plugin>   
  20.       </plugins>   
  21. </pluginManagement>   

 

 

子pom引用方法: 
在pom的build里的plugins引用: 

 

 

[html] view plain copy

  1. <plugins>   
  2.   <plugin>   
  3.     <groupId>org.apache.maven.plugins</groupId>   
  4.     <artifactId>maven-jar-plugin</artifactId>   
  5.   </plugin>   
  6. </plugins>  

build里的directories:

 

[html] view plain copy

  1. <sourceDirectory>${basedir}/src/main/java</sourceDirectory>   
  2. <scriptSourceDirectory>${basedir}/src/main/scripts</scriptSourceDirectory>   
  3. <testSourceDirectory>${basedir}/src/test/java</testSourceDirectory>   
  4. <outputDirectory>${basedir}/target/classes</outputDirectory>   
  5. <testOutputDirectory>${basedir}/target/test-classes</testOutputDirectory>  

这几个元素只在parent build element里面定义,他们设置多种路径结构,他们并不在profile里,所以不能通过profile来修改

 

build 里面的Extensions: 
它们是一系列build过程中要使用的产品,他们会包含在running bulid‘s classpath里面。他们可以开启extensions,也可以通过提供条件来激活plugins。简单来讲,extensions是在build过程被激活的产品 

[html] view plain copy

  1. <extensions>   
  2.   <extension>   
  3.     <groupId>org.apache.maven.wagon</groupId>   
  4.     <artifactId>wagon-ftp</artifactId>   
  5.     <version>1.0-alpha-3</version>   
  6.   </extension>   
  7. </extensions>   

reporting设置:

reporting包含site生成阶段的一些元素,某些maven plugin可以生成reports并且在reporting下配置。例如javadoc,maven site等,在reporting下配置的report plugin的方法与build几乎一样,最不同的是build的plugin goals在executions下设置,而reporting的configures goals在reporttest。

excludeDefaults:是否排除site generator默认产生的reports

outputDirectory,默认的dir变成:${basedir}/target/site

report sets:设置execution goals,相当于build里面的executions,不同的是不能够bind a report to another phase,只能够是site

 

[html] view plain copy

  1. <reporting>   
  2.     <plugins>   
  3.       <plugin>   
  4.         ...   
  5.         <reportSets>   
  6.           <reportSet>   
  7.             <id>sunlink</id>   
  8.             <reports>   
  9.               <report>javadoc</report>   
  10.             </reports>   
  11.             <inherited>true</inherited>   
  12.             <configuration>   
  13.               <links>   
  14.                 <link>http://java.sun.com/j2se/1.5.0/docs/api/</link>   
  15.               </links>   
  16.             </configuration>   
  17.           </reportSet>   
  18.         </reportSets>   
  19.       </plugin>   
  20.     </plugins>   
  21. </reporting>   

reporting里面的reportSets和build里面的executions的作用都是控制pom的不同粒度去控制build的过程,我们不单要配置plugins,还要配置那些plugins单独的goals。

更多项目信息:

name:项目除了artifactId外,可以定义多个名称
description: 项目描述
url: 项目url
inceptionYear:创始年份

Licenses

[html] view plain copy

  1. <licenses>  
  2.   <license>  
  3.     <name>Apache 2</name>  
  4.     <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>  
  5.     <distribution>repo</distribution>  
  6.     <comments>A business-friendly OSS license</comments>  
  7.   </license>  
  8. </licenses>  

列出本工程直接的licenses,而不要列出dependencies的licenses

配置组织信息:

[html] view plain copy

  1. <organization>  
  2.   <name>Codehaus Mojo</name>  
  3.   <url>http://mojo.codehaus.org</url>  
  4. </organization>  

很多工程都受到某些组织运行,这里设置基本信息

 

配置开发者信息:

例如:一个开发者可以有多个roles,properties是 

[html] view plain copy

  1. <developers>  
  2.     <developer>  
  3.       <id>eric</id>  
  4.       <name>Eric</name>  
  5.       <email>[email protected]</email>  
  6.       <url>http://eric.propellors.NET</url>  
  7.       <organization>Codehaus</organization>  
  8.       <organizationUrl>http://mojo.codehaus.org</organizationUrl>  
  9.       <roles>  
  10.         <role>architect</role>  
  11.         <role>developer</role>  
  12.       </roles>  
  13.       <timezone>-6</timezone>  
  14.       <properties>  
  15.         <picUrl>http://tinyurl.com/prv4t</picUrl>  
  16.       </properties>  
  17.     </developer>  
  18.   </developers>  
  19.    

环境设置:

issueManagement:bug跟踪管理系统,定义defect tracking system缺陷跟踪系统,比如有(bugzilla,testtrack,clearquest等).

例如:

 

[html] view plain copy

  1. <issueManagement>   
  2.   <system>Bugzilla</system>   
  3.   <url>http://127.0.0.1/bugzilla/</url>   
  4. </issueManagement>   

仓库:

Repositories:pom里面的仓库与setting.xml里的仓库功能是一样的。主要的区别在于,pom里的仓库是个性化的。比如一家大公司里的setting文件是公用 的,所有项目都用一个setting文件,但各个子项目却会引用不同的第三方库,所以就需要在pom里设置自己需要的仓库地址。

repositories:要成为maven2的repository artifact,必须具有pom文件在$BASE_REPO/groupId/artifactId/version/artifactId-version.pom 
BASE_REPO可以是本地,也可以是远程的。repository元素就是声明那些去查找的repositories 
默认的central Maven repository在http://repo1.maven.org/maven2/

 

[html] view plain copy

  1. <repositories>   
  2.     <repository>   
  3.       <releases>   
  4.         <enabled>false</enabled>   
  5.         <updatePolicy>always</updatePolicy>   
  6.         <checksumPolicy>warn</checksumPolicy>   
  7.       </releases>   
  8.       <snapshots>   
  9.         <enabled>true</enabled>   
  10.         <updatePolicy>never</updatePolicy>   
  11.         <checksumPolicy>fail</checksumPolicy>   
  12.       </snapshots>   
  13.       <id>codehausSnapshots</id>   
  14.       <name>Codehaus Snapshots</name>   
  15.       <url>http://snapshots.maven.codehaus.org/maven2</url>   
  16.       <layout>default</layout>   
  17.     </repository>   
  18. </repositories>   

release和snapshots:是artifact的两种policies,pom可以选择那种政策有效。 
enable:本别指定两种类型是否可用,true or false 
updatePolicy:说明更新发生的频率always 或者 never 或者 daily(默认的)或者 interval:X(X是分钟数) 

checksumPolicy:当Maven的部署文件到仓库中,它也部署了相应的校验和文件。您可以选择忽略,失败,或缺少或不正确的校验和警告。

layout:maven1.x与maven2有不同的layout,所以可以声明为default或者是legacy(遗留方式maven1.x)。

 

插件仓库:

pluginRepositories:与Repositories具有类似的结构,只是Repositories是dependencies的home,而这个是plugins 的home。

 

分发管理:

distributionManagement :管理distribution和supporting files。 

downloadUrl:是其他项目为了抓取本项目的pom’s artifact而指定的url,就是说告诉pom upload的地址也就是别人可以下载的地址。 
status:这里的状态不要受到我们的设置,maven会自动设置project的状态,有效的值:none:没有声明状态,pom默认的;converted:本project是管理员从原先的maven版本convert到maven2的;partner:以前叫做synched,意思是与partner repository已经进行了同步;deployed:至今为止最经常的状态,意思是制品是从maven2 instance部署的,人工在命令行deploy的就会得到这个;verified:本制品已经经过验证,也就是已经定下来了最终版。 
repository:声明deploy过程中current project会如何变成repository,说明部署到repository的信息。 

[html] view plain copy

  1. <repository>   
  2.   <uniqueVersion>false</uniqueVersion>   
  3.   <id>corp1</id>   
  4.   <name>Corporate Repository</name>   
  5.   <url>scp://repo1/maven2</url>   
  6.   <layout>default</layout>   
  7. </repository>   
  8. <snapshotRepository>   
  9.   <uniqueVersion>true</uniqueVersion>   
  10.   <id>propSnap</id>   
  11.   <name>Propellors Snapshots</name>   
  12.   <url>sftp://propellers.Net/maven</url>   
  13.   <layout>legacy</layout>   
  14. </snapshotRepository>   

id, name::唯一性的id,和可读性的name 
uniqueVersion:指定是否产生一个唯一性的version number还是使用address里的其中version部分。true or false 
url:说明location和transport protocol 
layout:default或者legacy

 

profiles:pom4.0的一个新特性就是具有根据environment来修改设置的能力

它包含可选的activation(profile的触发器)和一系列的changes。例如test过程可能会指向不同的数据库(相对最终的deployment)或者不同的dependencies或者不同的repositories,并且是根据不同的JDK来改变的。那么结构如下: 

[html] view plain copy

  1. <profiles>   
  2.   <profile>   
  3.     <id>test</id>   
  4.     <activation>...</activation>   
  5.     <build>...</build>   
  6.     <modules>...</modules>   
  7.     <repositories>...</repositories>   
  8.     <pluginRepositories>...</pluginRepositories>   
  9.     <dependencies>...</dependencies>   
  10.     <reporting>...</reporting>   
  11.     <dependencyManagement>...</dependencyManagement>   
  12.     <distributionManagement>...</distributionManagement>   
  13.   </profile>   
  14. </profiles>   

Activation: 
触发这个profile的条件配置如下例:(只需要其中一个成立就可以激活profile,如果第一个条件满足了,那么后面就不会在进行匹配。 

 

[html] view plain copy

  1. <profile>   
  2.   <id>test</id>   
  3.   <activation>   
  4.     <activeByDefault>false</activeByDefault>   
  5.     <jdk>1.5</jdk>   
  6.     <os>   
  7.       <name>Windows XP</name>   
  8.       <family>Windows</family>   
  9.       <arch>x86</arch>   
  10.       <version>5.1.2600</version>   
  11.     </os>   
  12.     <property>   
  13.       <name>mavenVersion</name>   
  14.       <value>2.0.3</value>   
  15.     </property>   
  16.     <file>   
  17.       <exists>${basedir}/file2.properties</exists>   
  18.       <missing>${basedir}/file1.properties</missing>   
  19.     </file>   
  20.   </activation>   

激活profile的方法有多个:setting文件的activeProfile元素明确指定激活的profile的ID,在命令行上明确激活Profile用-P flag 参数 

查看某个build会激活的profile列表可以用:mvn help:active-profiles 

五、Maven私服

 

(一)nexus安装

1. 安装nexus

下载nexus至本地目录

在命令提示符下,进入本地资源目录,敲入命令

nexus install

如有下列提示则证明安装成功。

如果想卸载,命令为:

nexus uninstall


2. 启动nexus

在服务中找到nexus ,右键启动

3. 进入nexus

打开浏览器输入地址:http://localhost:8081/nexus

点击右上角的Log In  ,在弹出窗口中输入username为admin ,password为admin123 ,点击Log In按钮

(二)构建索引

刚刚安装好的nexus是无法直接搜索到jar包的,必须下载索引才可以正常使用。

我们到中央仓库地址 http://repo.maven.apache.org/maven2/.index/下载以下两个索引压缩文件

nexus-maven-repository-index.gz
nexus-maven-repository-index.properties

这两个文件一般在此页面的最后的位置,另外还需要在网上下载一个名为indexer-cli-5.1.1.jar 的jar包

将以下三个文件放入一个文件夹

cmd执行:

java -jar indexer-cli-5.1.1.jar -u nexus-maven-repository-index.gz -d indexer

执行后生成目录indexer,目录下的文件是索引文件,如下图

将D:\nexus-2.12.0-01-bundle\sonatype-work\nexus\indexer\central-ctx 目录下的文件删除,将上边的索引文件拷贝到此目录下。

拷贝后重新启动nexus,然后进入nexus搜索jar包发现可以进行搜索了。

(三)仓库类型

1、hosted:宿主仓库,自己项目的jar要放到hosted类型的仓库中。

2、proxy:代理仓库,代理中央仓库

3、virtual:虚拟仓库,存储了maven1的构件,一般不用。

4、group:仓库组,将一些仓库组成一个组,自己项目连接仓库组去下载jar包。

       平常开发中都去连接仓库组,仓库组中包括:hosted、proxy等。

(四)镜像配置

nexus已经安装好了,我们要开始使用它了。现在我们需要在maven的配置文件settings.xml中配置镜像,让maven找私服,而不是直接到中央仓库下载。

打开maven的配置文件settings.xml,添加如下配置:

<mirrors>   

    <mirror>

      <id>nexus</id>

      <mirrorOf>*</mirrorOf>

      <url>http://localhost:8081/nexus/content/groups/public/</url>

    </mirror>

</mirrors>


mirrors为镜像组,可以配置多个mirror(镜像),我们这里配置的是nexus中的中央代理仓库。

配置好后,我们需要创建一个项目来测试一下,看看是不是可以通过nexus来下载jar包。

测试步骤:

创建maven工程(jar),在pom.xml中添加依赖,观察nexus中是否下载了相应的jar包,目录为 nexus-2.12.0-01-bundle\sonatype-work\nexus\storage\central

(五)发布自己的工程jar到nexus

1. 创建maven工程itcastutil (jar)

座标信息:  Group Id :cn.itcast.util 

           Artifact Id: itcastutil

创建包cn.itcast.util

创建类DateUtil

package cn.itcast.util;

 

import java.util.Calendar;

import java.util.Date;

/**

 * 日期工具类

 * @author Administrator

 *

 */

publicclass DateUtil {

   

    /**

     * 获取当前年份

     * @return

     */

    publicstaticint getYear(){

       

        Calendar calendar=Calendar.getInstance();

        calendar.setTime(new Date());

        return  calendar.get(Calendar.YEAR);

    }

}

在pom.xml中引入如下配置信息

<distributionManagement>

    <repository>

        <id>releases</id>

        <url>

             http://localhost:8081/nexus/content/repositories/releases/

       </url>

    </repository>

    <snapshotRepository>

        <id>snapshots</id>

        <url>

            http://localhost:8081/nexus/content/repositories/snapshots/

        </url>

    </snapshotRepository>

  </distributionManagement>


2. 在Maven中配置

将以下配置信息放入maven的settings.xml中

  <servers>

    <server>

      <id>releases</id>

      <username>admin</username>

      <password>admin123</password>

    </server>  

    <server>

      <id>snapshots</id>

      <username>admin</username>

      <password>admin123</password>

    </server>

  </servers>

注意:settings.xml 配置 <id>和 pom.xml<id> 对应!

然后执行命令  deploy  ,有如下提示表示部署成功

我们在私服中进行查询,发现可以查到刚才我们上传的jar

(六)发布第三方的工程jar到nexus

有很多jar包由于版权等问题,并不会出现在中央仓库中,比如oracle的驱动,那如何将这类jar包放在nexus中呢?我们看下列操作步骤:

(1)选择左侧菜单的Repositories,  在Repositories窗口中选择3rd party

(2)在3rd party窗口中选择Artifact Upload

(3)在Artifact Upload选项卡中填写座标,并上传jar包。

 

上传jar包选择oracle的驱动。

填写座标

有下列提示则为上传成功

上传成功后可以在3rd party库中找到此jar包

(七)从nexus中下载jar包

  1、对于所有项目,设置setting.xml

<profile>     
    <!--profile的id-->  
   <id>dev</id>     
    <repositories>     
      <repository>    
        <!--仓库id,repositories可以配置多个仓库,保证id不重复-->  
        <id>nexus</id>     
        <!--仓库地址,即nexus仓库组的地址-->  
        <url>http://localhost:8081/nexus/content/groups/public/</url>     
        <!--是否下载releases构件-->  
        <releases>     
          <enabled>true</enabled>     
        </releases>     
        <!--是否下载snapshots构件-->  
        <snapshots>     
          <enabled>true</enabled>     
        </snapshots>     
      </repository>     
    </repositories>    
     <pluginRepositories>    
        <!-- 插件仓库,maven的运行依赖插件,也需要从私服下载插件 -->  
        <pluginRepository>    
            <!-- 插件仓库的id不允许重复,如果重复后边配置会覆盖前边 -->  
            <id>public</id>    
            <name>Public Repositories</name>    
            <url>http://localhost:8081/nexus/content/groups/public/</url>    
        </pluginRepository>    
    </pluginRepositories>    
  </profile>    

  2、对於单个项目,设置pom.xml

 

<repositories>  
    <repository>  
      <releases>  
        <enabled>true</enabled>  
      </releases>  
      <snapshots>  
        <enabled>true</enabled>  
      </snapshots>  
      <id>nexus</id>  
      <url>http://localhost:8081/nexus/content/groups/public/</url>  
    </repository>  
    <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>  
      <id>public</id>  
      <name>Public Repositories</name>  
      <url>http://localhost:8081/nexus/content/groups/public/</url>  
    </pluginRepository>  
    <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>  

六、Maven常见问题

http://blog.csdn.net/heweirun_2014/article/details/46558329

个人言谈:广纳百川为一体,方得浩瀚于己身。

 

 

 

 

 


    

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章