如何使用maven构建项目

来源:互联网 发布:社工库数据下载 编辑:程序博客网 时间:2024/05/22 04:51
1.下载安装maven 
  到http://maven.apache.org下载一个最新版的,解压后即可,如果需要在命令行运行,还需要设置一些环境变量,环境可以这么配置比如说你的maven目录在d:\apache-maven-xxx.x,那么你的的系统环境变量需要这么来配置,类似于java的环境变量,配置MAVEN_HOME即为d:\apache-maven-xxx.x,然后配置PATH,为%MAVEN_HOME%\bin,安装成功后当你在命令行下执行maven -version后能正确显示当前maven的版本就说明你的maven安装成功了。 
2.创建maven项目 
首先先直接来给大家创建一个maven项目,之后再来细讲。首先进入某个盘比如说d:,建立项目mvn archetype:create -DgroupId=com.travelsky.app -DartifactId=travelsky -DarchetypeArtifactId=maven-archetype-webapp 
然后cmd进入刚建好的项目文件夹执行命令mvn package 然后再执行mvn eclipse:eclipse执行完毕之后用eclipse把该项目导入即可。 
maven命令大全 
    validate,验证工程是否正确,所有需要的资源是否可用。 
    compile,编译项目的源代码。 
    test-compile,编译项目测试代码。 
    test,使用已编译的测试代码,测试已编译的源代码。 
    package,已发布的格式,如jar,将已编译的源代码打包。 
    integration-test,在集成测试可以运行的环境中处理和发布包。 
    verify,运行任何检查,验证包是否有效且达到质量标准。 
    install,把包安装在本地的repository中,可以被其他工程作为依赖来使用 
    deploy,在整合或者发布环境下执行,将最终版本的包拷贝到远程的repository,使得其他的开发者或者工程可以共享。 
    generate-sources,产生应用需要的任何额外的源代码,如xdoclet。 
3.建立完maven项目之后会多一个pom 
  什么是pom? 
POM,即Project Object Model, 通过pom.xml文件配置Maven2,然后Maven2根据此配置执行。作用类似ant的build.xml文件,功能更强大。该文件用于管理:源代码、配置文件、开发者的信息和角色、问题追踪系统、组织信息、项目授权、项目的url、项目的依赖关系等等。 
快速察看: 
<project> 
  <modelVersion>4.0.0</modelVersion> 

  <!-- The Basics --> 
  <groupId>...</groupId> 
  <artifactId>...</artifactId> 
  <version>...</version> 
  <packaging>...</packaging> 
  <dependencies>...</dependencies> 
  <parent>...</parent> 
  <dependencyManagement>...</dependencyManagement> 
  <modules>...</modules> 
  <properties>...</properties> 

  <!-- Build Settings --> 
  <build>...</build> 
  <reporting>...</reporting> 

  <!-- More Project Information --> 
  <name>...</name> 
  <description>...</description> 
  <url>...</url> 
  <inceptionYear>...</inceptionYear> 
  <licenses>...</licenses> 
  <organization>...</organization> 
  <developers>...</developers> 
  <contributors>...</contributors> 

  <!-- Environment Settings --> 
  <issueManagement>...</issueManagement> 
  <ciManagement>...</ciManagement> 
  <mailingLists>...</mailingLists> 
  <scm>...</scm> 
  <prerequisites>...</prerequisites> 
  <repositories>...</repositories> 
  <pluginRepositories>...</pluginRepositories> 
  <distributionManagement>...</distributionManagement> 
  <profiles>...</profiles> 
</project> 

基本内容: 
    POM包括了所有的项目信息。 
maven 相关: 
pom定义了最小的maven2元素,允许groupId,artifactId,version。所有需要的元素 
• groupId:项目或者组织的唯一标志,并且配置时生成的路径也是由此生成,如org.codehaus.mojo生成的相对路径为:/org/codehaus/mojo 
• artifactId: 项目的通用名称 
• version:项目的版本 
• packaging: 打包的机制,如pom, jar, maven-plugin, ejb, war, ear, rar, par 
• classifier: 分类 
POM关系: 
主要为依赖,继承,合成 
  依赖关系: 
  <dependencies> 
    <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>4.0</version> 
      <type>jar</type> 
      <scope>test</scope> 
      <optional>true</optional> 
    </dependency> 
    ... 
  </dependencies> 
• groupId, artifactId, version:描述了依赖的项目唯一标志 
可以通过以下方式进行安装: 
•   使用以下的命令安装: 
•   mvn install:install-file –Dfile=non-maven-proj.jar –DgroupId=some.group –DartifactId=non-maven-proj –Dversion=1 
•   创建自己的库,并配置,使用deploy:deploy-file 
•   设置此依赖范围为system,定义一个系统路径。不提倡。 
• type:相应的依赖产品包形式,如jar,war 
• scope:用于限制相应的依赖范围,包括以下的几种变量: 
•   compile :默认范围,用于编译 
•   provided:类似于编译,但支持你期待jdk或者容器提供,类似于classpath 
•   runtime:在执行时,需要使用 
•   test:用于test任务时使用 
•   system:需要外在提供相应得元素。通过systemPath来取得 
• systemPath: 仅用于范围为system。提供相应的路径 
• optional: 标注可选,当项目自身也是依赖时。用于连续依赖时使用 
   独占性    
   外在告诉maven你只包括指定的项目,不包括相关的依赖。此因素主要用于解决版本冲突问题 
  <dependencies> 
    <dependency> 
      <groupId>org.apache.maven</groupId> 
      <artifactId>maven-embedder</artifactId> 
      <version>2.0</version> 
      <exclusions> 
        <exclusion> 
          <groupId>org.apache.maven</groupId> 
          <artifactId>maven-core</artifactId> 
        </exclusion> 
      </exclusions> 
    </dependency> 
表示项目maven-embedder需要项目maven-core,但我们不想引用maven-core 

继承关系 
    另一个强大的变化,maven带来的是项目继承。主要的设置: 
定义父项目 
<project> 
  <modelVersion>4.0.0</modelVersion> 
  <groupId>org.codehaus.mojo</groupId> 
  <artifactId>my-parent</artifactId> 
  <version>2.0</version> 
  <packaging>pom</packaging> 
</project> 
    packaging 类型,需要pom用于parent和合成多个项目。我们需要增加相应的值给父pom,用于子项目继承。主要的元素如下: 
• 依赖型 
• 开发者和合作者 
• 插件列表 
• 报表列表 
• 插件执行使用相应的匹配ids 
• 插件配置 
• 子项目配置 
<project> 
  <modelVersion>4.0.0</modelVersion> 
  <parent> 
    <groupId>org.codehaus.mojo</groupId> 
    <artifactId>my-parent</artifactId> 
    <version>2.0</version> 
    <relativePath>../my-parent</relativePath> 
  </parent> 
  <artifactId>my-project</artifactId> 
</project> 
relativePath可以不需要,但是用于指明parent的目录,用于快速查询。 

dependencyManagement: 
用于父项目配置共同的依赖关系,主要配置依赖包相同因素,如版本,scope。 

合成(或者多个模块) 
    一个项目有多个模块,也叫做多重模块,或者合成项目。 
如下的定义: 
<project> 
  <modelVersion>4.0.0</modelVersion> 
  <groupId>org.codehaus.mojo</groupId> 
  <artifactId>my-parent</artifactId> 
  <version>2.0</version> 
  <modules> 
    <module>my-project1<module> 
    <module>my-project2<module> 
  </modules> 
</project> 

build 设置 
    主要用于编译设置,包括两个主要的元素,build和report 
  build 
    主要分为两部分,基本元素和扩展元素集合 
注意:包括项目build和profile build 
<project> 
  <!-- "Project Build" contains more elements than just the BaseBuild set --> 
  <build>...</build> 
  <profiles> 
    <profile> 
      <!-- "Profile Build" contains a subset of "Project Build"s elements --> 
      <build>...</build> 
    </profile> 
  </profiles> 
</project> 

基本元素 
<build> 
  <defaultGoal>install</defaultGoal> 
  <directory>${basedir}/target</directory> 
  <finalName>${artifactId}-${version}</finalName> 
  <filters> 
    <filter>filters/filter1.properties</filter> 
  </filters> 
  ... 
</build> 
• defaultGoal: 定义默认的目标或者阶段。如install 
• directory: 编译输出的目录 
• finalName: 生成最后的文件的样式 
• filter: 定义过滤,用于替换相应的属性文件,使用maven定义的属性。设置所有placehold的值 

资源(resources) 
    你项目中需要指定的资源。如spring配置文件,log4j.properties 
<project> 
  <build> 
    ... 
    <resources> 
      <resource> 
        <targetPath>META-INF/plexus</targetPath> 
        <filtering>false</filtering> 
        <directory>${basedir}/src/main/plexus</directory> 
        <includes> 
          <include>configuration.xml</include> 
        </includes> 
        <excludes> 
          <exclude>**/*.properties</exclude> 
        </excludes> 
      </resource> 
    </resources> 
    <testResources> 
      ... 
    </testResources> 
    ... 
  </build> 
</project> 
• resources: resource的列表,用于包括所有的资源 
• targetPath: 指定目标路径,用于放置资源,用于build 
• filtering: 是否替换资源中的属性placehold 
• directory: 资源所在的位置 
• includes: 样式,包括那些资源 
• excludes: 排除的资源 
• testResources: 测试资源列表 
插件 
  在build时,执行的插件,比较有用的部分,如使用jdk 5.0编译等等 
<project> 
  <build> 
    ... 
    <plugins> 
      <plugin> 
        <groupId>org.apache.maven.plugins</groupId> 
        <artifactId>maven-jar-plugin</artifactId> 
        <version>2.0</version> 
        <extensions>false</extensions> 
        <inherited>true</inherited> 
        <configuration> 
          <classifier>test</classifier> 
        </configuration> 
        <dependencies>...</dependencies> 
        <executions>...</executions> 
      </plugin> 
    </plugins> 
  </build> 
</project> 
• extensions: true or false,是否装载插件扩展。默认false 
• inherited: true or false,是否此插件配置将会应用于poms,那些继承于此的项目 
• configuration: 指定插件配置 
• dependencies: 插件需要依赖的包 
• executions: 用于配置execution目标,一个插件可以有多个目标。 
如下: 
    <plugin> 
        <artifactId>maven-antrun-plugin</artifactId> 

        <executions> 
          <execution> 
            <id>echodir</id> 
            <goals> 
              <goal>run</goal> 
            </goals> 
            <phase>verify</phase> 
            <inherited>false</inherited> 
            <configuration> 
              <tasks> 
                <echo>Build Dir: ${project.build.directory}</echo> 
              </tasks> 
            </configuration> 
          </execution> 
        </executions> 
      </plugin> 
  说明: 
• id:规定execution 的唯一标志 
• goals: 表示目标 
• phase: 表示阶段,目标将会在什么阶段执行 
• inherited: 和上面的元素一样,设置false maven将会拒绝执行继承给子插件 
• configuration: 表示此执行的配置属性 

插件管理 
    pluginManagement:插件管理以同样的方式包括插件元素,用于在特定的项目中配置。所有继承于此项目的子项目都能使用。主要定义插件的共同元素 

扩展元素集合 
主要包括以下的元素: 
Directories 
用于设置各种目录结构,如下: 
  <build> 
    <sourceDirectory>${basedir}/src/main/java</sourceDirectory> 
    <scriptSourceDirectory>${basedir}/src/main/scripts</scriptSourceDirectory> 
    <testSourceDirectory>${basedir}/src/test/java</testSourceDirectory> 
    <outputDirectory>${basedir}/target/classes</outputDirectory> 
    <testOutputDirectory>${basedir}/target/test-classes</testOutputDirectory> 
    ... 
  </build> 

Extensions 

表示需要扩展的插件,必须包括进相应的build路径。 

<project> 
  <build> 
    ... 
    <extensions> 
      <extension> 
        <groupId>org.apache.maven.wagon</groupId> 
        <artifactId>wagon-ftp</artifactId> 
        <version>1.0-alpha-3</version> 
      </extension> 
    </extensions> 
    ... 
  </build> 
</project> 

Reporting 
    用于在site阶段输出报表。特定的maven 插件能输出相应的定制和配置报表。 
  <reporting> 
    <plugins> 
      <plugin> 
        <outputDirectory>${basedir}/target/site</outputDirectory> 
        <artifactId>maven-project-info-reports-plugin</artifactId> 
        <reportSets> 
          <reportSet></reportSet> 
        </reportSets> 
      </plugin> 
    </plugins> 
  </reporting> 

Report Sets 
    用于配置不同的目标,应用于不同的报表 
<reporting> 
    <plugins> 
      <plugin> 
        ... 
        <reportSets> 
          <reportSet> 
            <id>sunlink</id> 
            <reports> 
              <report>javadoc</report> 
            </reports> 
            <inherited>true</inherited> 
            <configuration> 
              <links> 
                <link>http://java.sun.com/j2se/1.5.0/docs/api/</link> 
              </links> 
            </configuration> 
          </reportSet> 
        </reportSets> 
      </plugin> 
    </plugins> 
  </reporting> 

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

Licenses 
<licenses> 
  <license> 
    <name>Apache 2</name> 
    <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> 
    <distribution>repo</distribution> 
    <comments>A business-friendly OSS license</comments> 
  </license> 
</licenses> 

Organization 
配置组织信息 
  <organization> 
    <name>Codehaus Mojo</name> 
    <url>http://mojo.codehaus.org</url> 
  </organization> 

Developers 
配置开发者信息 
<developers> 
    <developer> 
      <id>eric</id> 
      <name>Eric</name> 
      <email>eredmond@codehaus.org</email> 
      <url>http://eric.propellors.net</url> 
      <organization>Codehaus</organization> 
      <organizationUrl>http://mojo.codehaus.org</organizationUrl> 
      <roles> 
        <role>architect</role> 
        <role>developer</role> 
      </roles> 
      <timezone>-6</timezone> 
      <properties> 
        <picUrl>http://tinyurl.com/prv4t</picUrl> 
      </properties> 
    </developer> 
  </developers> 

Contributors 
  <contributors> 
    <contributor> 
      <name>Noelle</name> 
      <email>some.name@gmail.com</email> 
      <url>http://noellemarie.com</url> 
      <organization>Noelle Marie</organization> 
      <organizationUrl>http://noellemarie.com</organizationUrl> 
      <roles> 
        <role>tester</role> 
      </roles> 
      <timezone>-5</timezone> 
      <properties> 
        <gtalk>some.name@gmail.com</gtalk> 
      </properties> 
    </contributor> 
  </contributors> 

环境设置 

Issue Management 
    定义相关的bug跟踪系统,如bugzilla,testtrack,clearQuest等 
  <issueManagement> 
    <system>Bugzilla</system> 
    <url>http://127.0.0.1/bugzilla</url> 
  </issueManagement> 
Continuous Integration Management 
连续整合管理,基于triggers或者timings 
  <ciManagement> 
    <system>continuum</system> 
    <url>http://127.0.0.1:8080/continuum</url> 
    <notifiers> 
      <notifier> 
        <type>mail</type> 
        <sendOnError>true</sendOnError> 
        <sendOnFailure>true</sendOnFailure> 
        <sendOnSuccess>false</sendOnSuccess> 
        <sendOnWarning>false</sendOnWarning> 
        <configuration><address>continuum@127.0.0.1</address></configuration> 
      </notifier> 
    </notifiers> 
  </ciManagement> 

Mailing Lists 
  <mailingLists> 
    <mailingList> 
      <name>User List</name> 
      <subscribe>user-subscribe@127.0.0.1</subscribe> 
      <unsubscribe>user-unsubscribe@127.0.0.1</unsubscribe> 
      <post>user@127.0.0.1</post> 
      <archive>http://127.0.0.1/user/</archive> 
      <otherArchives> 
        <otherArchive>http://base.google.com/base/1/127.0.0.1</otherArchive> 
      </otherArchives> 
    </mailingList> 
  </mailingLists> 

SCM 
  软件配置管理,如cvs 和svn 
  <scm> 
    <connection>scm:svn:http://127.0.0.1/svn/my-project</connection> 
    <developerConnection>scm:svn:https://127.0.0.1/svn/my-project</developerConnection> 
    <tag>HEAD</tag> 
    <url>http://127.0.0.1/websvn/my-project</url> 
  </scm> 

以上即为pom文件的具体配置解释。 

4.maven有他的私服 也就是nexus 作为maven的中央仓库 

向maven中导入非官方的jar:mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> 
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging> 

去下载nexus-oss-webapp-1.7.0-bundle.zip,然后解压缩到任意目录下(如E:\nexus) 
下载地址:http://nexus.sonatype.org/downloads/ 
如果操作系统是windows-x86-32 则 进入目录 
E:\nexus\nexus-oss-webapp-1.7.0\bin\jsw\windows-x86-32运行nexus.bat在浏览器中输入http://localhost:8081/nexus/index.html 
即可进入登录页面 默认用户名密码是admin/admin123 
接着说pox.xml文件 
配置MAVEN使用NEXUS作为镜像仓库,首先找到${home.dir}/.m2/settings.xml 
文件 如果没有.m2文件夹的话,说明你没有运行过MVN,请在命令行中输入MVN命 
令,首次运行MAVEN后会自动创建.M2文件夹,然后进入MAVEN的安装路径下的 
CONF文件夹,把默认settings.xml 拷贝到${home.dir}/.m2下。接着在此文件中填入以下信息: 
<?xml version="1.0" encoding="UTF-8"?> 
<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"> 
  <mirrors> 
    <mirror> 
      <!--This sends everything else to /public --> 
      <id>nexus</id> 
      <mirrorOf>*</mirrorOf> 
      <url>http:// 主机ip:端口/nexus/content/groups/public</url> 
    </mirror> 
  </mirrors> 
  <profiles> 
    <profile> 
      <id>nexus</id> 
      <!--Enable snapshots for the built in central repo to direct --> 
      <!--all requests to nexus via the mirror --> 
      <repositories> 
        <repository> 
          <id>xinxin</id> 
          <url>http://主机ip:端口/nexus/content/groups/public</url> 
          <releases><enabled>true</enabled></releases> 
          <snapshots><enabled>true</enabled></snapshots> 
        </repository> 
      </repositories> 
     <pluginRepositories> 
        <pluginRepository> 
          <id>xinxin</id> 
          <url>http:// 主机ip:端口/nexus/content/groups/public</url> 
          <releases><enabled>true</enabled></releases> 
          <snapshots><enabled>true</enabled></snapshots> 
        </pluginRepository> 
      </pluginRepositories> 
    </profile> 
  </profiles> 
  
  <activeProfiles> 
    <!--make the profile active all the time --> 
    <activeProfile>nexus</activeProfile> 
  </activeProfiles> 
</settings> 

注意:Nexus默认是关闭远程索引下载的,主要是担心会造成对服务器的巨大负担。常用的需要开启的三个仓库分别是Maven Center,Apache Snapshots,Codehaus Snapshots;具体的开启方式(以Maven Center为例): 
左侧窗口点击Repositories,右侧会将所有仓库信息显示出来,选中代理仓库Maven Center, 更改Configuration->Download Remote Indexes为true,保存配置后,右击代理仓库Maven Center然后选择ReIndex,如此即可触发Nexus下载远程的索引文件。 

5. Nexus中配置自己的数据仓库,及仓库管理 
  添加一个新的仓库(以添加host仓库为例) 
首先以管理员身份登录Nexus,左边导航栏Views/repositories点击Repositories,这样会在右边新窗口列出所有的已知仓库,。 
然后点击新窗口左上角的Add按钮,下拉选项中我们选在Host Repositories,这样就打开了一个新增Host数据仓库页面,接下来要做的就是根据自己的需要按照提示填写配置信息,填写完成记得点击save按钮保存。 
默认的Local Storage Location会保存在Nexus安装主目录下的\sonatype-work\nexus\storage路径下,如果需要改动,在Overridding Local Storage Location项输入相应的路径即可。因为我们maven中配置的公共仓库组是在public Repostitories组中,所以我们需要把新建的仓库添加至public Repostitories.具体操做如下: 
   在仓库列表中选中public Repostitories,Configuration –>Available Repositories下将新建仓库(我们这里的新建仓库名为test)拖拽至Ordered Group Repositories,点击save按钮保存配置。 
这部操作的时候你可能会疑惑为什么看不到我刚添加的仓库呢,那是因为nexus没刷新,你可以点击刷新按钮刷新下就可以添加了。 
  给自己的仓库里面上传自己本地的jar包: 
   选中仓库,选择Artifact Upload。Artifact Upload下一共有两个模块:select GAV Defination source 和 select Artifact(s) for Upload,我们首先在select Artifact(s) for Upload 模块下点击select Artifact(s) for upload按钮上传构件,然后在select GAV Defination source模块填写相关构件配置参数Classifier是用来区分同一版本号的不同版本,如poi-3.0-FINAL.jar,FINAL就是它的Classifier.另外Nexus对构件命名校验很严格,一般规则是“构建名+版本号[+Classifier].构建类型” ,上传时的相关参数填写和Maven的pom.xml配置依赖稍微不匹配就可能导致取不到构件。这点一定要注意。 
完成保存之后,一定要记得重建索引不然是不会被发现的。 
0 0