在Eclipse中使用Maven 2.x指南

1.Maven 2 Repository

Eclipse需要知道Maven的本地倉庫的路徑。所以,類路徑變量M2_REPO必須設置。執行以下命令:

mvn -Declipse.workspace=<path-to-eclipse-workspace> eclipse:add-maven-repo

 

你也可以在eclipse內定義一個新的classpath變量:從菜單條,選擇Window>Preferences,選擇java>Build Path>Classpath變量頁。進入eclipse,導入workspace下面的Sample Project。由於缺少MAVEN_REPO變量,Eclipse提示編譯失敗。EclipsePreferences – Java - Build Path - Classpath Variables中添加名爲MAVEN_REPO的變量,指向D:/maven/local/repository

如果想讓eclipse支持直接運行mavengoal,可以安裝mavenide插件。

 

2.把Maven作爲外部工具

可能需要從eclipse執行一些maven goals,這可以通過配置外部裝載器實現。爲eclise添加一個變量,指向本地maven的可執行文件(mvn.bat/mvn)。從菜單條,選擇Window>Preferences,選擇Run/Debug>String Substitution,增加一個新的變量,比如maven_exec。當你設置新的外部裝載器(叢菜單條,選擇Run>External Tools,選擇Program),你可以在位置字段引用剛纔定義的maven_exec。進一步,引用project_log作爲工作目錄,指定所選的maven goals作爲參數,比如eclipse:eclipse。更多的信息請參考eclipse的幫助。

 

問題:如果插件可以產生變量和runner可能會好一點。

3.一個簡單例子

如果你有一個單模塊的簡單java項目,使用eclipse將十分簡單。爲了從你的POM產生eclipse項目文件,執行以下命令:

mvn eclipse:eclipse

如果你已經使用eclipse創建或者檢出了項目,你只需在workspace中刷新項目。否則,你必須將項目導入eclipse工作空間(從菜單條選擇File>Import>Existing Projects into Workspace)。在後面的例子,項目(目錄)不應在你的workspace,因爲eclipse可能導致錯誤,特別是你將eclipse作爲scm客戶端時。

 

4.多模塊項目

Due to the workspace idea many eclipse users are used to a flat layout and therefore want to keep this structure, which is possible but not recommended. Actually, the only reason for a flat multiple module project layout is the possibility to checkout and edit the parent POM without checking out the whole project. The following sample shows how to handle maven multiple module projects with eclipse while keeping the recommended hierachical project layout.

 

假設eclipse是你的SCM客戶端,這個例子將告訴你如何設置一個新的多模塊項目。

1.     設置一個新的叫做step-by-step的workspace,並且象上面所述增加M2_REPO類路徑。

2.     打開命令行shell,並且切換到新建的工作空間(workspace)目錄。

3.     從命令行使用archetype插件新建一個maven項目

mvn archetype:create -DgroupId=guide.ide.eclipse -DartifactId=guide-ide-eclipse

 

 

 

4.     step-by-step工作空間,使用eclipse創建一個新的簡單項目guide-ide-eclipse(從菜單條,選擇File>New>Project,選擇Simple>Project)。Eclipse會爲你的guide-ide-eclipse項目創建一個簡單的.project文件,你應該能夠看到一個pom.xml文件。

5.     刪除src文件夾,並且打開pom.xml文件,將父項目的packaging改爲pom。

<packaging>pom</packaging>

問題:mvn eclipse:eclipse也許應該爲pom packaging類型產生一個簡單的.project文件。

 

6.     從命令行切換到guide-ide-eclipse項目路徑,並且創建一些模塊:

cd guide-ide-eclipse

mvn archetype:create -DgroupId=guide.ide.eclipse -DartifactId=guide-ide-eclipse-site

mvn archetype:create -DgroupId=guide.ide.eclipse.core -DartifactId=guide-ide-eclipse-core

mvn archetype:create -DgroupId=guide.ide.eclipse.module1 -DartifactId=guide-ide-eclipse-module1

 

 

7.     將新建的模塊添加到父pom中。

  <modules>

    <module>guide-ide-eclipse-site</module>

    <module>guide-ide-eclipse-core</module>

    <module>guide-ide-eclipse-module1</module>

  </modules>

 

8.     在新建的模塊的POMs中添加parent。

  <parent>

        <groupId>guide.ide.eclipse</groupId>

        <artifactId>guide-ide-eclipse</artifactId>

        <version>1.0-SNAPSHOT</version>

  </parent>

 

9.     添加模塊間依賴:

    <dependency>

      <groupId>guide.ide.eclipse.core</groupId>

      <artifactId>guide-ide-eclipse-core</artifactId>

      <version>1.0-SNAPSHOT</version>

    </dependency>

 

10.  把項目安裝到本地倉庫,並且產生eclipse文件:

mvn install

mvn eclipse:eclipse

 

11.  使用eclipse的團隊開發支持(從context菜單選擇Team>Share Project)檢入項目。記住,不要檢入產生的eclipse文件。如果使用CVS,你因該在每個模塊有一個.cvsignore文件,內容如下:

target

.classpath

.project

.wtpmodules

即使是父項目,也應該有.cvsignore文件。當你從repository檢出項目時,Eclipse自動生成新的簡單的.project文件。

 

問題:插件應該可選的產生.cvsignore文件。

 

現在,你有不同的處理選項。如果你同時工作於所有模塊,你應該具有eclipse的項目依賴,而不是二進制依賴,你可以設置一個新的workspace,並且從step-by-step/guide-ide-eclipse中導入。記住,你必須先刪除父項目的.project文件。結果和從命令行檢出整個項目相同,運行mvn eclipse:eclipse並且最後把項目導入到你的eclipse工作空間。兩種方式都可以使用eclipse同步你對項目的修改。

 

對於有許多人蔘與的大項目而言,檢出所有模塊並且保持更新是一件相當乏味的工作。特別是你只對其中某(幾)個模塊感興趣。這種情況,使用二進制依賴更合適。只要在eclipse上檢出你需要工作的模塊,然後爲每個模塊運行mvn eclipse:eclipse。當然所有用到的artifacts在你的maven倉庫中必須可用。

 

扁平項目佈局:

有可能將父POM從自己的目錄搬移到和模塊相同級別的目錄。

1、guide-ide-eclipse下創建一個名爲guide-ide-eclipse-project的新目錄,並且將父POM搬移到這個目錄。

2、對父POM修改模塊引用:

  <modules>

    <module>../guide-ide-eclipse-site</module>

    <module>../guide-ide-eclipse-core</module>

    <module>../guide-ide-eclipse-module1</module>

  </modules>

 

問題:發佈(releasee)插件不支持扁平結構。

 

Introduction to the Build Lifecycle(1)

8.構建生命週期介紹

8.1.構建生命週期基礎

Maven 2是以構建生命週期爲中心概念的。這意味着構建和分發一個特定的artifact是被清晰定義的。

 

項目有生命週期(lifecycle),生命週期中有一系列階段,每個階段都和一組goals綁定,goals由插件提供。

 

對於構建項目的人來說,只要學習一些命令就可以來構建所有的Maven項目,並且POM保證他們能獲得期望的結果。

 

對於一個項目來說,會可能使用以下公共生命週期階段:

Ø       Validate – 驗證項目正確性,以及所有必要的信息是否齊備;

Ø       Compile – 編譯項目源代碼;

Ø       Test – 使用單元測試框架測試編譯過的源代碼。這些測試無需代碼被打包或者部署;

Ø       Package – 將編譯過的代碼打包,如JAR

Ø       Integration-test – 爲了集成測試能夠進行,處理和部署應用到合時的環境;

Ø       Verify – 檢查和檢驗package是否有效並且符合質量要求;

Ø       Install – package安裝到本地倉庫,供本地其他項目使用(作爲依賴項);

Ø       Deploy – 在集成或者發佈環境中,將最終的package拷貝到遠程倉庫,供其它開發人員或者項目共享。

 

記住,對於每個階段,所有它之前的生命週期階段都會執行,所以,你在命令行只要指定最後的那個就行。比如:

mvn install

如果執行這個命令的話,會編譯、測試、打包、校驗和安裝package到本地倉庫。

 

同時,同樣的命令可以在多模塊場景中使用。比如:

mvn clean install

這個命令會遍歷所有的子項目,對每個子項目執行cleaninstall(包括所有install之前的階段)。

 

8.2.設置項目以使用構建生命週期

使用構建生命週期是比較簡單的,但當你爲一個項目創建一個Maven 構建時,如何將任務分配給那些構建階段呢?

8.2.1.Packaging

首先,是設置項目的packaging,默認爲jar,所以不管你是否指定,packaging都會發生。每個packaging包含一系列綁定到特定階段的goals。比如,對於JAR,會有以下goals綁定到生命週期:

階段

Goal

Process-resources

Resources:resources

Compile

Compiler:compile

Precess-test-resources

Resources:testResources

Test-compile

Compiler:testCompile

Test

Surefire:test

Package

Jar:jar

Install

Install:install

Deploy

Deploy:deploy

這是標準的一組綁定;然而,有些打包處理不同,比如,一個項目僅僅有元數據,那麼只要綁定installdeploy階段。

 

記住,對於一些packaging類型,你需要在pom.xml文件的build節包含特定的plugin。一個例子就是Plexus插件,它提供了plexus-applicationplexus-service packaging

 

8.2.2.插件

第二種對階段增加goals的方法就是在項目中配置插件。插件包含每個goal綁定到哪個階段的信息。記住,僅僅增加插件還不夠,你必須同時指定你需要的goals

 

這些配置的goals將會加入到由packaging綁定到生命週期的goals。如果綁定到特定階段的goal超過一個,那麼來自packaginggoal會先執行,然後執行在POM配置的goal。可以通過executions元素控制特定goals的順序。

 

比如,Modello插件將modello:java綁定到generate-souces階段,使用Modello插件從模型產生源代碼,你必須將以下內容加入到POMplugins節:

...

 <plugin>

   <groupId>org.codehaus.modello</groupId>

   <artifactId>modello-maven-plugin</artifactId>

   <executions>

     <execution>

       <configuration>

         <model>maven.mdo</model>

         <modelVersion>4.0.0</modelVersion>

       </configuration>

       <goals>

         <goal>java</goal>

       </goals>

     </execution>

   </executions>

 </plugin>

...

你可能會覺得奇怪,那兒爲什麼會有executions元素,這可以讓你在需要時,使用不同的配置多次運行相同的goal。不同的execution可以給於不同的id,這樣當用於繼承或者應用profiles時,你就可以控制goal配置是否合併或者變成附加的execution中。

 

當有多個executions匹配一個階段(phase)時,他們以POM中指定的順序執行,來自繼承的executions首先運行。

 

對於modello:java,它只對generate-source階段(phase)有意義。不過某些goals可以用於多個階段,並且沒有默認值,對於這種情況,你可以(必須)自己指定階段(phase)。比如,假設有一個goal touch:timestamp,用於將當前時間顯示到文件中,你需要在process-test-resources階段用它來指出測試是何時開始的,可以像下面那樣配置:

...

 <plugin>

   <groupId>com.mycompany.example</groupId>

   <artifactId>touch-maven-plugin</artifactId>

   <executions>

     <execution>

       <phase>process-test-resources</phase>

       <configuration>

         <file>${project.output.directory}/timestamp.txt</file>

       </configuration>

       <goals>

         <goal>timestamp</goal>

       </goals>

     </execution>

   </executions>

 </plugin>

...

 

Maven 2 介紹(5)

7.7.6.創建WEB應用程序

Now we want to use this library in a Web application. For simplicity, our Web application will consist of a JavaServer Pages (JSP) file that directly invokes the HotelModel class. First, we create a new Web application project using the archetype plug-in:

現在,要將此類庫應用到一個web應用程序。爲了簡單,我們的web應用程序將由一個jsp文件直接調用HotelModel類。首先,我們使用archetype插件創建一個新的web應用項目:

mvn archetype:create -DgroupId=com.javaworld.hotels -
DartifactId=HotelWebapp -Dpackagename=com.javaworld.hotels -
DarchetypeArtifactId=maven-archetype-webapp

 

 

Next, we need to include our business logic JAR in this application. All we need to do is to add a dependency to the new pom.xml, pointing to our HotelDatabase component:

接着,我們需要將業務邏輯JAR包含進此web應用程序。我們所需做的事情就是加入一個依賴項到此新的pom.xml文件,並指向我們的HotelDatabase組件:

    <dependency>
      <groupId>com.javaworld.hotels</groupId>
      <artifactId>HotelDatabase</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>

Now we implement the main (and only) JSP page. It simply lists the available cities and, if a city is chosen, lists the corresponding hotels:

現在,我們實現主要的JSP頁面。它僅簡單的列出所有可用的城市,如果選擇了某個城市,就列出相應的賓館:

<html>
<body>
<h2>Hotel database tutorial application</h2>
<%@ page import="
   java.util.List,
    com.javaworld.hotels.businessobjects.Hotel,
    com.javaworld.hotels.model.HotelModel"
%>
<%
   HotelModel model = new HotelModel();

   String[] cityList = model.findAvailableCities();

   String selectedCity = request.getParameter("city");
   List<Hotel> hotelList = model.findHotelsByCity(selectedCity);
%>

   <h3>Choose a destination</h3>
   <form action="index.jsp" method="get">
     Please choose a city:
      <SELECT name="city">
         <OPTION value="">---Any city---</OPTION>
         <%
         for(String cityName : cityList){
         %>
          <OPTION value="<%=cityName%>"><%=cityName%></OPTION>
         <%
         }
         %>
      </SELECT>
      <BUTTON type="submit">GO</BUTTON>
   </form>
   <% if (hotelList.size() > 0) { %>
      <h3>Available hotels in <%=selectedCity%> </h3>
      <table border="1">
           <tr>
             <th>Name</th>
             <th>Address</th>
             <th>City</th>
             <th>Stars</th>
            </tr>
         <%
         for(Hotel hotel : hotelList){
         %>
           <tr>
             <td><%=hotel.getName()%></td>
             <td><%=hotel.getAddress()%></td>
             <td><%=hotel.getCity()%></td>
             <td><%=hotel.getStars()%> stars</td>
            </tr>
         <%
         }
         %>
       </table>
    <%}%>
</body>
</html>

 

 

Now run mvn install from the HotelWebapp directory; this will compile, bundle, and deploy the HotelWebapp.war file to your local repository (you can also find it in the target directory if you need to). Now you can deploy this war file to your favorite application server and see what you get (see Figure 4).

 

現在,從HotelWebapp目錄運行mvn install命令,這將編譯、打包並且部署HotelWebapp.war文件到你的本地倉庫(你也可以從target目錄找到它)。現在,你可以把此war文件部署到你熟悉的應用服務器,並且可以看到如下的頁面:

 

Figure 4. The tutorial application in action

7.7.7.使用插件

Maven 2 comes with an ever-increasing number of plug-ins that add extra functions to your build process with little effort. To use a plug-in, you bind it to a lifecycle phase. Maven will then figure out when (and how) to use it. Some plug-ins are already used by Maven behind the scenes, so you just have to declare them in the plugins section of your pom.xml file. The following plug-in, for example, is used to compile with J2SE 1.5 source code:

 

Maven 2含有乙一組數量不斷增長的插件,用來爲你的構建過程增加額外的功能。爲了使用插件,你需要將它綁定到生命週期階段。Maven將指出何時(以及如何)使用它們。一些組件,Maven在背後已經使用了,所以你只要在pom.xml文件的plugins節聲明它們。以下插件,用來編譯J2SE 1.5的源代碼:

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

 

 

 In other cases, you bind the plug-in to a lifecycle phase so that Maven will know when to use it. In the following example, we want to run some standard Ant tasks. To do this, we bind the maven-antrun-plugin to the generate-sources phase, and add the Ant tasks between the tasks tags, as shown here:

另外,你可以將插件和某個生命週期階段綁定,這樣,Maven就會知道何時使用它們。下面的例子,我們要運行一些標準的Ant任務。爲了達到這個目的,我們將maven-antrun-plugin插件綁定到generate-sources階段,並且把ant任務插入到tasks標記處,如下所示:

...
  <build>
    ...
    <plugins>
       <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <executions>
            <execution>
              <phase>generate-sources</phase>
              <configuration>            
                <tasks>
                  <!-- Ant tasks go here -->
                </tasks>
              </configuration>
              <goals>
                <goal>run</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
     </plugins>    
  </build>

 

 

7.7.4.使用Maven2進行單元測試

Now let's test the application. A few simple test classes can be found in the source code. Unit testing is (or should be!) an important part of any enterprise Java application. Maven completely integrates unit testing into the development lifecycle. To run all your unit tests, you invoke the test lifecycle phase:

現在來測試應用程序,在源代碼中可以找到一些簡單測試類。單元測試是(或者應該是)任何企業java應用程序的重要組成部分。Maven將單元測試完全集成進了開發生命週期。要運行所有的單元測試,可以調用test生命週期階段:

mvn test

 

 

If you want to run only one test, you can use the test parameter:

如果你只想運行某個單元測試,可以使用test參數指定:

mvn test -Dtest=HotelModelTest

 

 

A nice feature of Maven 2 is its use of regular expressions and the test parameter to control the tests you want to run. If you want to run only one test, you just indicate the name of the test class:

Maven 2的一個特性是test參數使用規則表達式來運行測試,如果只想運行某個測試,你只要指出測試類的名稱就可以了:

mvn test -Dtest=HotelModelTest

 

 

If you want to run only a subset of the unit tests, you can use a standard regular expression. For example, to test all ModelTest classes:

如果你想運行一組單元測試,可以使用標準的規則表達式,比如,爲了測試所有的ModelTest類:

mvn test -Dtest=*ModelTest

 

 

7.7.5.構建和部署JAR

Once you're happy with the tests, you can build and deploy your new JAR. The install command compiles, tests, and bundles your classes into a jar file and deploys it to your local Maven 2 repository, where it can be seen by other projects:

一旦完成了單元測試,就可以構建和部署新的JARInstall命令編譯、測試和將所有的類文件打包成一個jar文件,並把此jar文件部署到你的本地Maven 2倉庫中。

mvn install

 

 Maven 2 介紹(3)

7.7.應用實例

Now that we have seen a few of the basic notions used in Maven 2, let's see how it works in the real world. The rest of this tutorial examines how we would use Maven 2 on a simple Java Enterprise Edition project. The demo application involves an imaginary (and simplified) hotel database system. To demonstrate how Maven handles dependencies between projects and components, this application will be built using two components (see Figure 3):

 

現在,讓我們來看一些Maven 2中的基本標記,看看它們如何工作。以下部分用Maven 2來開發一個簡單的java企業級應用項目。示例應用程序涉及到虛構的(簡化的)賓館數據庫系統。爲了介紹Maven如何處理項目以及組件之間的依賴,這個應用使用兩個組件(子項目)。

  • A business logic component: HotelDatabase.jar
  • A Web application component: HotelWebApp.war

 

Figure 3. The tutorial application architecture involves two simple components: a JAR (HotelDatabase.jar) and a WAR (HotelWebapp.war)

You can download the source code to follow along with the tutorial in Resources.

 

7.7.1.設置項目環境

We start by configuring your work environment. In real-world projects, you will often need to define and configure environment or user-specific parameters that should not be distributed to all users. If you are behind a firewall with a proxy, for example, you need to configure the proxy settings so that Maven can download JARs from repositories on the Web. For Maven 1 users, the build.properties and project.properties files do this job. In Maven 2, they have been replaced by a settings.xml file, which goes in the $HOME/.m2 directory. Here is an example:

 

我們從配置工作環境起步。在真實項目中,你經常需要定義和配置環境或者用戶指定的參數,這些環境和參數不和其他用戶共享。如果你使用防火牆,那麼你需要配置代理服務器,讓Maven可以從遠程倉庫下載JARs。對於Maven 1的用戶,由build.propertiesproject.properties文件來做這項工作,而在Maven 2中,則由$HOME/.m2目錄下的settings.xml文件來做這項工作:

<?xml version="1.0" encoding="UTF-8"?>
<settings>
  <proxies>
    <proxy>
      <active/>
      <protocol>http</protocol>
      <username>scott</username>
      <password>tiger</password>
      <port>8080</port>
      <host>my.proxy.url</host>
      <id/>
    </proxy>
  </proxies>
</settings>

 

7.7.2.使用archetype插件創建新項目

The next step is to create a new Maven 2 project template for the business logic component. Maven 2 provides the archetype plug-in, which builds an empty Maven 2-compatible project directory structure. This plug-in proves convenient for getting a basic project environment up and running quickly. The default archetype model will produce a JAR library project. Several other artifact types are available for other specific project types, including Web applications, Maven plug-ins, and others.

接下來,就是爲業務邏輯組件創建一個新的Maven 2項目模板。Maven 2提供了archetype插件,用來創建空的、兼容Maven 2的項目目錄結構。這個插件爲快速建立基本項目環境提供了方便。默認的archetype模型將產生JAR庫項目。其他一些artifact類型可用來創建其他指定的項目類型,包括WEB應用程序,Maven插件等等。

 

Run the following command to set up your HotelDatabase.jar project:

運行以下命令來創建你的HoteDatabase.jar項目:

mvn archetype:create -DgroupId=com.javaworld.hotels -
   DartifactId=HotelDatabase -Dpackagename=com.javaworld.hotels

Now you have a brand new Maven 2 project directory structure. Switch to the HotelDatabase directory to continue the tutorial.

現在,你有了一個新的Maven 2項目目錄結構,切換到HotelDatabase目錄,繼續此嚮導。

7.7.3.實現業務邏輯

Now we implement the business logic. The Hotel class is a simple JavaBean. The HotelModel class implements two services: the findAvailableCities() method, which lists available cities, and the findHotelsByCity() method, which lists all hotels in a given city. A simple, memory-based implementation of the HotelModel class is presented here:

現在,我們實現業務邏輯,Hotel類是一個簡單的JavaBean。而HotelModel類實現兩個服務:findAvailabelCities()方法,列出所有能夠獲得的城市;

findHotelsByCity()方法,則依據給定的城市獲取賓館列表。

以下是一個簡單的,基於內存實現的HotelModel類:

package com.javaworld.hotels.model;

import java.util.ArrayList;
import java.util.List;

import com.javaworld.hotels.businessobjects.Hotel;

public class HotelModel {

   /**
    * The list of all known cities in the database.
    */
   private static String[] cities =
   {
      "Paris",
      "London",
   };
  
   /**
    * The list of all hotels in the database.
    */
   private static Hotel[] hotels = {
      new Hotel("Hotel Latin","Quartier latin","Paris",3),
      new Hotel("Hotel Etoile","Place de l'Etoile","Paris",4),
      new Hotel("Hotel Vendome","Place Vendome","Paris",5),
      new Hotel("Hotel Hilton","Trafalgar Square","London",4),
      new Hotel("Hotel Ibis","The City","London",3),
   };
  
   /**
    * Returns the hotels in a given city.
    * @param city the name of the city
    * @return a list of Hotel objects
    */
   public List<Hotel> findHotelsByCity(String city){
      List<Hotel> hotelsFound = new ArrayList<Hotel>();
      
      for(Hotel hotel : hotels) {
         if (hotel.getCity().equalsIgnoreCase(city)) {
            hotelsFound.add(hotel);
         }
      }      
      return hotelsFound;
   }  
  
   /**
    * Returns the list of cities in the database which have a hotel.
    * @return a list of city names
    */
   public String[] findAvailableCities() {
      return cities;
   }
}

 

 

7.3.項目生命週期

Project lifecycles are central to Maven 2. Most developers are familiar with the notion of build phases such as compile, test, and deploy. Ant has targets with names like those. In Maven 1, corresponding plug-ins are called directly. To compile Java source code, for instance, the java plug-in is used:

 

項目生命週期是Maven 2的中心。大多數開發人員熟悉構建階段的一些標記,比如compile,test,以及deployAnttargets的名稱也和這個類似。在Maven 1中,相應的插件是直接調用的,爲了編譯Jave源代碼,使用java插件:

$maven java:compile

In Maven 2, this notion is standardized into a set of well-known and well-defined lifecycle phases (see Figure 2). Instead of invoking plug-ins, the Maven 2 developer invokes a lifecycle phase:

Maven 2中,這些標記被標準化到一組衆所周知的、明確的生命週期階段(參見圖2)。在Maven 2中,開發人員直接調用生命週期階段,而不是調用插件:

$mvn compile.

 

 

 

Figure 2. Maven 2 lifecycle phases

Some of the more useful Maven 2 lifecycle phases are the following: 以下是一些有用的Maven 2生命週期階段:

  • generate-sources: Generates any extra source code needed for the application, which is generally accomplished using the appropriate plug-ins 。生成額外的應用程序所需的源代碼,通常由相應插件獲得。
  • compile: Compiles the project source code 。編譯項目源代碼。
  • test-compile: Compiles the project unit tests 。編譯項目單元測試源代碼。
  • test: Runs the unit tests (typically using JUnit) in the src/test directory。運行src/test目錄下的單元測試 (通常使用junit)。
  • package: Packages the compiled code in its distributable format (JAR, WAR, etc.) 。以分發的格式(jar,war等等)打包。
  • integration-test: Processes and deploys the package if necessary into an environment where integration tests can be run 。集成測試。
  • install: Installs the package into the local repository for use as a dependency in other projects on your local machine 。安裝包到本地倉庫,作爲你本機的其他項目的依賴項。
  • deploy: Done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects。在集成和發佈環境下使用,拷貝最終的包到遠程倉庫,分享給其他開發人員和項目。

Many other lifecycle phases are available. See Resources for more details.

These phases illustrate the benefits of the recommended practices encouraged by Maven 2: once a developer is familiar with the main Maven 2 lifecycle phases, he should feel at ease with the lifecycle phases of any Maven project.

還有許多其他生命週期階段。這些階段闡明瞭使用Maven 2推薦的開發實踐的好處:一旦一個開發人員熟悉了主要的Maven 2生命週期階段,他就會易於接受其他Maven項目的生命週期階段。

 

The lifecycle phase invokes the plug-ins it needs to do the job. Invoking a lifecycle phase automatically invokes any previous lifecycle phases as well. Since the lifecycle phases are limited in number, easy to understand, and well organized, becoming familiar with the lifecycle of a new Maven 2 project is easy.

生命週期階段調用它所需的插件來完成任務。調用一個生命週期階段自動調用所有在它之前的生命週期階段。由於生命週期階段在數量上有限,易於理解,組織良好,理解一個使用Maven 2的新項目的生命週期是相對容易的事情。

 

7.4.及物依賴Transitive dependencies

One of the highlights of Maven 2 is transitive dependency management. If you have ever used a tool like urpmi on a Linux box, you'll know what transitive dependencies are. With Maven 1, you have to declare each and every JAR that will be needed, directly or indirectly, by your application. For example, can you list the JARs needed by a Hibernate application? With Maven 2, you don't have to. You just tell Maven which libraries you need, and Maven will take care of the libraries that your libraries need (and so on).

Maven 2的一大亮點就是及物依賴管理。如果你使用過象Linux平臺上的urpmi的工具,你會知道什麼是及物依賴。在Maven 1中,你必須聲明你所需要的每個應用程序直接或者間接需要的JAR。比如,Hibernate應用程序所需的JARs就有很多。在Maven 2中,你不必如此,你只要告訴Maven你所需要的庫,Maven會照顧到你的庫所需要的庫。

 

Suppose you want to use Hibernate in your project. You would simply add a new dependency to the dependencies section in pom.xml, as follows:

假設你在項目中需要使用Hibernate,你只要簡單的在pom.xml文件的dependencies節中加入一個新的dependency,如下所示:

<dependency>
      <groupId>hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.0.3</version>
      <scope>compile</scope>
   </dependency>

And that's it! You don't have to hunt around to know in which other JARs (and in which versions) you need to run Hibernate 3.0.3; Maven will do it for you!

這就夠了!你不必知道運行Hibernate 3.0.3需要哪些JARs,以及它們的版本,Maven會爲你做這些工作!

 

The XML structure for dependencies in Maven 2 is similar to the one used in Maven 1. The main difference is the scope tag, which is explained in the following section.

 

7.5.依賴範圍

In a real-world enterprise application, you may not need to include all the dependencies in the deployed application. Some JARs are needed only for unit testing, while others will be provided at runtime by the application server. Using a technique called dependency scoping, Maven 2 lets you use certain JARs only when you really need them and excludes them from the classpath when you don't.

在實際企業應用程序中,你可能無需包含所有的依賴項到你的部署應用程序中,有些JARs只有單元測試需要,而有些可能由應用服務器提供。使用稱爲依賴範圍的技術,Maven 2讓你使用那些你需要的JARs,而在不需要時則從classpath排除它們。

Maven provides four dependency scopes: Maven提供了4個依賴範圍

  • compile: A compile-scope dependency is available in all phases. This is the default value. 編譯時依賴在所有階段都可獲得,這是默認值。
  • provided: A provided dependency is used to compile the application, but will not be deployed. You would use this scope when you expect the JDK or application server to provide the JAR. The servlet APIs are a good example. Provided依賴範圍用來編譯應用程序,但無需部署。若你用到jdk或者應用服務器提供的JAR,則使用此範圍,servlet APIs就屬於這個依賴範圍。
  • runtime: Runtime-scope dependencies are not needed for compilation, only for execution, such as JDBC (Java Database Connectivity) drivers. 運行依賴範圍在編譯階段是不需要的,只有在運行時需要,比如JDBC驅動程序。
  • test: Test-scope dependencies are needed only to compile and run tests (JUnit, for example). 測試範圍依賴,僅在編譯和運行單元測試時需要(比如Junit)。

7.6.項目溝通

An important part of any project is internal communication. While it is not a silver bullet, a centralized technical project Website can go a long way towards improving visibility within the team. With minimal effort, you can have a professional-quality project Website up and running in very little time.

任何項目中,內部溝通都是一個重要部分,一個集中的項目技術網站可以顯著提高開發組內的溝通能力。通過Maven 2,你能夠輕易的創建一個專業級的項目網站。

 

This takes a whole new dimension when the Maven site generation is integrated into a build process using continuous integration or even automatic nightly builds. A typical Maven site can publish, on a daily basis:

Maven站點產生功能使用持續集成或者自動每日構建,集成到構建過程中後,將會帶來一個全新的境界。典型的Maven站點能夠每日發佈:

  • General project information such as source repositories, defect tracking, team members, etc. 一般項目信息,比如源代碼庫,缺失跟蹤,小組成員等等。
  • Unit test and test coverage reports 。單元測試以及測試覆蓋報表。
  • Automatic code reviews and with Checkstyle and PMD 。使用CheckstylePMD自動進行代碼reviews
  • Configuration and versioning information。配置和版本信息。
  • Dependencies 。依賴項
  • Javadoc
  • Source code in indexed and cross-referenced HTML format。索引的以及交叉引用的HTML格式的源代碼。
  • Team member list 。小組成員列表。
  • And much more。以及其他。

Once again, any Maven-savvy developer will immediately know where to look to become familiar with a new Maven 2 project.

再重申一下,任何熟悉Maven的開發人員將能夠快速的熟悉另一個新的基於Maven 2的項目。
Maven 2 介紹(1)

7.Maven 2介紹

Maven is a popular open source build tool for enterprise Java projects, designed to take much of the hard work out of the build process. Maven uses a declarative approach, where the project structure and contents are described, rather then the task-based approach used in Ant or in traditional make files, for example. This helps enforce company-wide development standards and reduces the time needed to write and maintain build scripts.

 

Maven是一個流行的構建企業級java項目的開源構建工具,它的設計目標是將一些構建過程中的繁重工作剝離出來。Maven使用宣告式的方法,項目的結構和內容是被描述的,而不是像使用ant或者傳統make文件那樣基於任務的方法。這樣可以加強企業範圍內的開發標準,並且減少編寫和維護構建腳本的時間。

 

The declarative, lifecycle-based approach used by Maven 1 is, for many, a radical departure from more traditional build techniques, and Maven 2 goes even further in this regard. In this article, I go through some of the basic principals behind Maven 2 and then step through a working example. Let's start by reviewing the fundamentals of Maven 2.

 

宣告式的,基於生命週期的方法在Maven 1中就已經得到應用,在這方面,Maven 2走的更遠。先來看一下Maven 2的基礎。

7.1.項目對象模型

The heart of a Maven 2 project is the project object model (or POM for short). It contains a detailed description of your project, including information about versioning and configuration management, dependencies, application and testing resources, team members and structure, and much more. The POM takes the form of an XML file (pom.xml), which is placed in your project home directory. A simple pom.xml file is shown here:

Maven 2項目的核心是項目對象模型,縮寫爲POM。項目對象模型包括對項目的詳細描述,包括項目的版本信息、配置管理、依賴、應用和測試資源、開發組成員和結構、以及更多。POM採用XML文件方式(pom.xml),放置在項目的根目錄下,下面是一個pom.xml文件的示例:

<project xmlns="http://maven.apache.org/POM/4.0.0"

  xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

  http://maven.apache.org/maven-v4_0_0.xsd">

   <modelVersion>4.0.0</modelVersion>

   <groupId>com.javaworld.hotels</groupId>

   <artifactId>HotelDatabase</artifactId>

   <packaging>war</packaging>

   <version>1.0-SNAPSHOT</version>

   <name>Maven Quick Start Archetype</name>

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

   <dependencies>

<dependency>

         <groupId>junit</groupId>

         <artifactId>junit</artifactId>

         <version>3.8.1</version>

         <scope>test</scope>

  </dependency>

</dependencies>

</project>

 

 

7.2.Maven 2項目目錄結構

Much of Maven's power comes from the standard practices it encourages. A developer who has previously worked on a Maven project will immediately feel familiar with the structure and organization of a new one. Time need not be wasted reinventing directory structures, conventions, and customized Ant build scripts for each project. Although you can override any particular directory location for your own specific ends, you really should respect the standard Maven 2 directory structure as much as possible, for several reasons:

 

Maven的魔力來自於他所鼓勵的標準實踐。一個經歷過使用Maven開發項目的開發人員會馬上對新的項目結構和組織感到熟悉。這樣就無需浪費對每個項目重新熟悉目錄結構,約定以及定製ANT構建腳本的時間。儘管你可以用自己的方式覆蓋任何特定的目錄位置,你還是應該儘量遵從標準Maven 2的目錄結構:

  • It makes your POM file smaller and simpler (使你的POM文件簡短)
  • It makes the project easier to understand and makes life easier for the poor guy who must maintain the project when you leave (使項目易於理解)
  • It makes it easier to integrate plug-ins(易於集成插件)

The standard Maven 2 directory structure is illustrated in Figure 1. In the project home directory goes the POM (pom.xml) and two subdirectories: src for all source code and target for generated artifacts.

 

標準的Maven 2目錄結構如圖1所示。項目主目錄下有一個POM(pom.xml)以及兩個子目錄:src放置所有的源代碼,target目錄放置構建產生的文件。

 

Figure 1. The standard Maven 2 directory layout

The src directory has a number of subdirectories, each of which has a clearly defined purpose:

 

src目錄有一些子目錄,每個子目錄都有清晰定義的目的:

  • src/main/java: Your Java source code goes here (strangely enough!) java源代碼目錄
  • src/main/resources: Other resources your application needs 。應用程序所需的資源目錄。
  • src/main/filters: Resource filters, in the form of properties files, which may be used to define variables only known at runtime。資源過濾文件,屬性文件格式,用於定義運行時所需得變量。
  • src/main/config: Configuration files。配置文件。
  • src/main/webapp: The Web application directory for a WAR projectWAR項目的web應用程序目錄
  • src/test/java: Unit tests。單元測試源代碼。
  • src/test/resources: Resources to be used for unit tests, but will not be deployed 。用於單元測試的資源,不會被部署。
  • src/test/filters: Resources filters to be used for unit tests, but will not be deployed 。單元測試所用到的資源過濾,不會被部署。
  • src/site: Files used to generate the Maven project Website。用於產生maven項目web站點的目錄。
MAVEN指南(8)

5.2.parent

artifactId

父項目的artifact標識符

groupId

父項目的group標識符

version

父項目的版本

relativePath

父項目的pom.xml文件的相對路徑。默認值爲../pom.xml。maven首先從當前構建項目開始查找父項目的pom文件,然後從本地倉庫,最有從遠程倉庫。RelativePath允許你選擇一個不同的位置。

 

5.3.prerequisites

項目的先決條件

maven

構建此項目所需的maven的最低版本

 

5.4.issueManagement

用於管理此項目的發佈跟蹤(bug跟蹤)。

system

構建此項目所需的maven的最低版本

url

此項目使用的發佈管理系統的URL。

 

5.5.ciManagement

system

持續集成系統的名稱,比如,continuum。

url

此項目使用的持續集成系統的URL,如果有WEB界面的話。

notifiers

配置用戶信息和通知模式,當構建成功通知開發人員/用戶,

 

5.6.notifier

配置通知方法,當構建中斷時通知用戶/開發人員。

Type

投遞通知的機制

SendOnError

是否發送錯誤通知

SendOnFailure

是否發送失敗通知

SendOnSuccess

是否發送成功通知

SendOnWarning

是否發送警告通知

Address

Deprecated。發送通知的地址,通常爲email地址

Configuration

附加配置信息

 

5.7.mailingList

此項目的郵件列表。自動產生的站點將引用此信息。

Name

郵件列表的名稱

Subscribe

訂閱此郵件列表的email地址或連接。如果是email地址,產生文檔時會自動生成mailto:連接

Unsubscribe

退訂此郵件列表的email地址或連接。如果是email地址,產生文檔時會自動生成mailto:連接

Post

可以投遞到此郵件列表的email地址或連接。如果是email地址,產生文檔時會自動生成mailto:連接

Archive

可以瀏覽到郵件列表存檔信息的URL。

OtherArchives

可選的替代URLs,用於瀏覽郵件存檔信息列表

 

 

MAVEN指南(7)

5.1.project元素

<project>元素爲描述符的根元素,以下列表列出它的所有子元素:

parent

父項目的位置,父項目中的值就是此項目中未指定的值的默認值。父項目的位置由group ID,artifact ID和version指定。

modelVersion

聲明此POM項目描述符所遵從的版本

groupId

一個全局唯一的項目標識符。通常使用完全限定的包名來和其它項目區隔(比如,org.apache.maven)

artifactId

在給定gorup ID內唯一的產品標識符。Artifact就是由項目產生的,或者由項目所使用的東西。比如由Maven項目產生的artifacts包括:JARs,source以及二進制分發包和WARs。

packaging

此項目產生的artifact的類型,比如jar,war,ear pom。插件能夠創建他們自己的packaging,所以,這裏並沒有列出所有可能的類型。

name

項目的名稱

version

此項目產生的artifact的當前版本。

description

此項目的詳細描述,被maven用來在需要的地方描述項目,比如web站點。而此元素可以使用CDATA,讓description裏可以包含HTML標籤。

url

項目主頁的URL。

prerequisites

描述此項目構建環境的先決條件

issueManagement

描述此項目的發佈管理系統信息

ciManagement

此項目的持續集成信息

inceptionYear

此項目開始年份,用四位整數指定。當產生版權信息時使用

mailingLists

項目的郵件列表信息

developers

項目的開發小組

contributors

項目的貢獻者,但不屬於開發小組

licenses

本項目的許可。這裏的許可是對本項目的許可,而不是對依賴項的許可。如果有多個許可,那麼用戶可以選擇其中之一,而不必全部。

scm

指定此項目使用的源代碼控制系統,如CVS等等。

organization

描述此項目所屬的機構。

build

構建此項目所需的信息。

profiles

項目本地構建文件列表,如果使用,可改變默認構建過程。

modules

作爲本項目一部分的模塊(子項目)。

repositories

查找發現依賴項和擴展項的遠程倉庫。

pluginRepositories

查找發現構建和報表所需插件的遠程倉庫。

dependencies

此項目的所有依賴項列表。這些依賴項在構建過程中用於構造所需的classpath。這些依賴項在構建時會自動下載。

reports

Deprecated。Maven現在忽略此元素。

reporting

此元素包含用於在Maven產生的項目站點中產生報表的插件的規格。這些報表在執行mvn site命令時運行,所有報表出現在導航條上。

dependencyManagement

所有項目的依賴信息繼承於此。這一節中的依賴項並不馬上解析。事實上,當一個繼承於此的POM使用groupId和artifactId定義一個依賴項時,當版本信息和其他信息沒有指定時,纔會使用這裏的依賴項定義。

distributionManagement

此項目的分發信息。

properties

POM可以用作替代,以及用於資源過濾。

 

MAVEN指南(6)

2.16.配置報表

maven提供了多種報表,你可以把它們加入到你的web站點上,用於顯示項目的當前狀態。這些報表都通過插件獲得。

 

爲了給你的站點添加報表,必須在POM的reporting節加入插件。下面的例子顯示如何配置標準的項目信息報表。

<project>

  ...

  <reporting>

    <plugins>

      <plugin>

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

        <artifactId>maven-project-info-reports-plugin</artifactId>

      </plugin>

    </plugins>

  </reporting>

  ...

 

如果在site.xml中包含有${reports},那麼產生的站點中將出現這些報表。

2.17.國際化

maven中,國際化是非常簡單的。

爲了允許使用多個locales,按如下配置就可以了:

<project>

  ...

  <build>

    <plugins>

      <plugin>

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

        <artifactId>maven-site-plugin</artifactId>

        <configuration>

          <locales>en,fr</locales>

        </configuration>

      </plugin>

    </plugins>

  ...

這樣,就會同時產生一個英語和法語的站點版本。如果en是你的當前locale,那麼,它會在站點的根目錄下,而法語翻譯版本則在fr/子目錄下。

 

爲了取代默認的翻譯內容,可以在站點目錄下放置一個以locale的名字爲名稱的子目錄,同時,創建該locale的站點描述符文件,比如:

+- src/

   +- site/

      +- apt/

      |  +- index.apt     (Default version)

      +- fr/

      |  +- apt/

      |  |  +- index.apt  (French version)

      +- site.xml         (Default site descriptor)

      +- site_fr.xml      (French site descriptor)

 

通過創建相關語言的站點描述符,翻譯的站點就可以獨立發展了。

 

2.18.如何構建其它類型的項目?

注意,生命週期將會被應用到任何項目類型。比如,退回到基目錄,可以創建一個簡單的web應用程序。

mvn archetype:create /

    -DgroupId=com.mycompany.app -DartifactId=my-webapp /

    -DarchetypeArtifactId=maven-archetype-webapp</source>

這個命令必須在一行內。運行此命令後,將會創建一個my-webapp的目錄,同時包含如下項目描述符:

<project>

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-webapp</artifactId>

  <packaging>war</packaging>

  <version>1.0-SNAPSHOT</version>

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

  <build>

    <finalName>my-webapp</finalName>

  </build>

</project>

 

注意到packaging元素,告訴maven構建一個WAR,嘗試以下命令:

mvn clean package

可以看到target/my-webapp.war被構建。

 

2.19.如何一次構建多個項目?

Maven2.0支持多模塊的概念。這裏,我們顯示如何構建上述的war,同時包含以前步驟的jar文件。

首先,在兩個項目的父目錄裏,需要創建一個新的父pom.xml文件,如下所示:

+- pom.xml

+- my-app

| +- pom.xml

+- my-webapp

| +- pom.xml

 

pom.xml文件包含如下內容:

<project>

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <version>1.0-SNAPSHOT</version>

  <artifactId>app</artifactId>

  <packaging>pom</packaging>

  <modules>

    <module>my-app</module>

    <module>my-webapp</module>

  </modules>

</project>

Webapp項目需要添加對jar項目的依賴項:

  .

  .

  .

  <dependencies>

    <dependency>

      <groupId>com.mycompany.app</groupId>

      <artifactId>my-app</artifactId>

      <version>1.0-SNAPSHOT</version>

    </dependency>

    .

    .

    .

最後,同時在兩個模塊的pom.xml文件中加入以下內容:

<project>

  <parent>

    <groupId>com.mycompany.app</groupId>

    <artifactId>app</artifactId>

    <version>1.0-SNAPSHOT</version>

  </parent>

  .

  .

  .

現在,在頂層目錄,運行以下命令:

mvn clean install

這時,創建了my-webapp/target/my-webapp.war,它包含了my-app-1.0-SNAPSHOT.jar

$ jar tvf my-webapp/target/my-webapp-1.0-SNAPSHOT.war

   0 Fri Jun 24 10:59:56 EST 2005 META-INF/

 222 Fri Jun 24 10:59:54 EST 2005 META-INF/MANIFEST.MF

   0 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/

   0 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/com.mycompany.app/

   0 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/com.mycompany.app/my-webapp/

3239 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/com.mycompany.app/my-webapp/pom.xml

   0 Fri Jun 24 10:59:56 EST 2005 WEB-INF/

 215 Fri Jun 24 10:59:56 EST 2005 WEB-INF/web.xml

 123 Fri Jun 24 10:59:56 EST 2005 META-INF/maven/com.mycompany.app/my-webapp/pom.properties

  52 Fri Jun 24 10:59:56 EST 2005 index.jsp

   0 Fri Jun 24 10:59:56 EST 2005 WEB-INF/lib/

2713 Fri Jun 24 10:59:56 EST 2005 WEB-INF/lib/my-app-1.0-SNAPSHOT.jar

這是怎樣工作的呢?首先,創建了父POM(名爲app),它包含了一組模塊,這就告訴maven,對這組模塊項目進行操作(可以通過使用—non-recursive命令行選項覆蓋此行爲)。

 

接着,我們告訴WAR項目需要my-app jar文件,這樣,使此jar出現在了classpath上,war項目中的所有代碼都可以使用它。Jar項目總是在war項目之前構建,並且告訴war插件在lib目錄包含那個jar文件。

 

你可能注意到junit-3.8.1.jar也是一個依賴項,但卻沒有出現war的lib目錄,因爲scope元素被設爲test,只有測試才需要junit-3.8.1.jar。

 

最後,就是在模塊pom.xml文件中包含parent定義。這和maven1.0中的extend元素不同:確保POM總是能夠定位,即使項目和其父分佈在不同地點,只要可以通過庫查找。

 

 

你可以在頂層目錄,通過以下命令來產生IDEA的工作空間:

mvn idea:idea

 

MAVEN指南(5)

2.10.如何把jar文件部署到自己的遠程庫?

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-app</artifactId>

  <packaging>jar</packaging>

  <version>1.0-SNAPSHOT</version>

  <name>Maven Quick Start Archetype</name>

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

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

    <dependency>

      <groupId>org.apache.codehaus.plexus</groupId>

      <artifactId>plexus-utils</artifactId>

      <version>1.0.4</version>

    </dependency>

  </dependencies>

  <build>

    <filters>

      <filter>src/main/filters/filters.properties</filter>

    </filters>

    <resources>

      <resource>

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

        <filtering>true</filtering>

      </resource>

    </resources>

  </build>

  <!--

   |

   |

   |

   -->

  <distributionManagement>

    <repository>

      <id>mycompany-repository</id>

      <name>MyCompany Repository</name>

      <url>scp://repository.mycompany.com/repository/maven2</url>

    </repository>

  </distributionManagement>

</project>

 

 

<settings>

  .

  .

  <servers>

    <server>

      <id>mycompany-repository</id>

      <username>jvanzyl</username>

      <!-- Default value is ~/.ssh/id_dsa -->

      <privateKey>/path/to/identity</privateKey> (default is ~/.ssh/id_dsa)

      <passphrase>my_key_passphrase</passphrase>

    </server>

  </servers>

  .

  .

</settings>

 

 

2.11.如何創建文檔?

爲了快速啓用maven的文檔系統,在項目尚不存在的情況下,可以使用archetype機制爲你產生站點。使用如下命令:

mvn archetype:create -DgroupId=com.mycompany.app

-DartifactId=my-app -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-site

 

 

如果你看一下產生的項目目錄結構,可以看到如下內容:

my-app

|-- pom.xml

`-- src

    |-- main

    |   |-- filters

    |   |   `-- filters.properties

    |   |-- java

    |   |   `-- com

    |   |       `-- mycompany

    |   |           `-- app

    |   |               `-- App.java

    |   `-- resources

    |       `-- META-INF

    |           |-- application.properties

    |           `-- application.properties~

    |-- site

    |   |-- apt

    |   |   |-- format.apt

    |   |   `-- index.apt

    |   |-- fml

    |   |   `-- faq.fml

    |   |-- fr

    |   |   |-- apt

    |   |   |   |-- format.apt

    |   |   |   `-- index.apt

    |   |   |-- fml

    |   |   |   `-- faq.fml

    |   |   `-- xdoc

    |   |       `-- xdoc.xml

    |   |-- site.xml

    |   |-- site_fr.xml

    |   `-- xdoc

    |       `-- xdoc.xml

    `-- test

        |-- java

        |   `-- com

        |       `-- mycompany

        |           `-- app

        |               `-- AppTest.java

        `-- resources

            `-- test.properties

 

注意到現在多了一個${basedir}/src/site目錄,裏面有站點描述符和所支持的各種文檔類型。

 

Xdoc格式,和maven1.0中一樣,只是把navigation.xml杯替換成了站點表述符。

APT格式,基本爲文本格式,類似於wiki格式,可以用來編寫簡單的,結構畫的文檔。請參考《APT格式》。

 

FML格式,FAQ格式,在maven1.0中也有。

 

還有其它格式。

 

Maven支持幾種輸出格式,但對於2.0,只支持XHTML格式。

 

2.12.如何創建站點?

使用如下命令:

mvn site

產生的站點位於target/site/目錄

 

2.13.如何部署站點?

爲了部署站點,必須首先在pom.xml文件中定義一個分發位置。

<distributionManagement>

  <site>

    <id>website</id>

    <url>scp://www.mycompany.com/www/docs/project/</url>

  </site>

</distributionManagement>

 

Id元素用於標識庫,所以在settings.xml文件中,可以和其它庫一樣附加安全憑據。Url給出了部署位置。當前,僅支持SSH,上面的配置將把站點拷貝到www.mycompany.com站點的/www/docs/project目錄。

 

部署站點使用site-deploy goal。

mvn site-deploy

 

 

 

2.14.創建站點描述符

site.xml文件用來描述站點的佈局。

示例:

<?xml version="1.0" encoding="ISO-8859-1"?>

<project name="Maven">

  <bannerLeft>

    <name>Maven</name>

    <src>http://maven.apache.org/images/apache-maven-project.png</src>

    <href>http://maven.apache.org/</href>

  </bannerLeft>

  <bannerRight>

    <src>http://maven.apache.org/images/maven-small.gif</src>

  </bannerRight>

  <body>

    <links>

      <item name="Apache" href="http://www.apache.org/" />

      <item name="Maven 1.0" href="http://maven.apache.org/"/>

      <item name="Maven 2" href="http://maven.apache.org/maven2/"/>

    </links>

 

    <menu name="Maven 2.0">

      <item name="Introduction" href="index.html"/>

      <item name="Download" href="download.html"/>

      <item name="Release Notes" href="release-notes.html" />

      <item name="General Information" href="about.html"/>

      <item name="For Maven 1.0 Users" href="maven1.html"/>

      <item name="Road Map" href="roadmap.html" />

    </menu>

 

    ${reports}

 

    ...

  </body>

</project>

 

裏面的${reports}將會被配置的報表替換。

 

2.15.添加額外的資源

可以在站點的資源目錄包含任意的資源,比如增加CSS

+- src/

   +- site/

      +- resources/

         +- css/

         |  +- site.css

         |

         +- images/

            +- pic1.jpg

文件site.css將被用於默認的XHTML輸出,可以用它來調整maven默認的樣式。

 

文件pic1.jpg可以在站點中的任何頁面引用。

2.8.如何過濾資源文件?

有時候,資源文件中的某些值在構建時才確定,爲了在maven中做到這點,使用${<property name>}語法將屬性引用放到資源文件中。這個屬性的值可以在你的pom.xml文件中定義,或者在用戶的settings.xml文件中,或者在外部屬性文件中,或者系統屬性。

爲了讓maven過濾資源,只要在pom.xml的resource節將filtering設爲true。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-app</artifactId>

  <packaging>jar</packaging>

  <version>1.0-SNAPSHOT</version>

  <name>Maven Quick Start Archetype</name>

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

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

  <build>

    <resources>

      <resource>

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

        <filtering>true</filtering>

      </resource>

    </resources>

  </build>

</project>

 

注意到我們加入了以前沒有的build,resoucses,resource元素,另外,我們必須明確的指定資源的位置,這裏爲src/main/resources目錄,所有這些以前都是作爲默認值的,但因爲filtering的默認值爲false,我們必須把這些都加入到pom.xml中,覆蓋默認設置。

 

爲了引用在pom.xml中定義的屬性,屬性名稱使用XML元素來定義值,“pom”允許作爲項目根元素的別名。所以${pom.name}指向項目的名稱,而${pom.version}指向項目的版本,${pom.build.finalName}指向最後創建的打包文件的名稱,等等。注意,某些POM元素有默認值,所以沒有必要在pom.xml文件中顯式定義。同樣的,在用戶settings.xml文件中的值可以通過以“settings”開頭的屬性名字來引用(比如,${settings.localRepository}指向用戶本地庫的路徑)。

 

爲了繼續我們的例子,在application.properties文件中加入一對屬性

# application.properties

application.name=${pom.name}

application.version=${pom.version}

 

在這裏,執行以下命令(process-resources是構建生命週期中的一個拷貝、過濾資源的階段)

mvn process_resources

 

爲了引用外部文件中定義的屬性,必須在pom.xml文件中增加對此外部文件的引用。首先,創建一個外部屬性文件,假設爲src/main/filters/filter.properties。

# filter.properties

my.filter.value=hello!

 

 

接下來,我們在pom.xml文件中增加對此外部資源文件的引用:

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-app</artifactId>

  <packaging>jar</packaging>

  <version>1.0-SNAPSHOT</version>

  <name>Maven Quick Start Archetype</name>

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

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

  <build>

    <filters>

      <filter>src/main/filters/filter.properties</filter>

    </filters>

    <resources>

      <resource>

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

        <filtering>true</filtering>

      </resource>

    </resources>

  </build>

</project>

 

然後,如果我們在application.properties文件中加入屬性引用

# application.properties

application.name=${pom.name}

application.version=${pom.version}

message=${my.filter.value}

 

再次執行mvn processs-resources命令,將會把新屬性的值放入application.properties文件中。作爲在外部文件中定義my.filter.value屬性的替代,你可以在pom.xml中定義properties節,可以獲得同樣的效果。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-app</artifactId>

  <packaging>jar</packaging>

  <version>1.0-SNAPSHOT</version>

  <name>Maven Quick Start Archetype</name>

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

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

  <build>

    <resources>

      <resource>

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

        <filtering>true</filtering>

      </resource>

    </resources>

  </build>

  <properties>

    <my.filter.value>hello</my.filter.value>

  </properties>

</project>

 

資源過濾同樣可以從系統屬性中獲取值;比如java的內建屬性(java.version或者user.home)或者命令行定義的屬性(使用java –D參數)。

# application.properties

java.version=${java.version}

command.line.prop=${command.line.prop}

 

 

現在,當執行以下命令後,application.properties文件將包含系統屬性的值:

mvn process-resources "-Dcommand.line.prop=hello again"

 

 

2.9.如何使用外部依賴項?

你可能已經注意到在示例中的POM中已經使用了dependencies元素。更全面的介紹,請參考《依賴項管理介紹》。

 

Pom.xml文件中的dependencies節列出了所有構建時需要的外部依賴項(不管是編譯時、測試時、運行時)。示例中,目前只用到了Junit。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-app</artifactId>

  <packaging>jar</packaging>

  <version>1.0-SNAPSHOT</version>

  <name>Maven Quick Start Archetype</name>

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

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

</project>

 

 

對於每個外部依賴項,必須定義4樣東西:goupId,artifactId,version以及scope。GroupId,artifactId以及version元素沒有什麼特別,scope元素指明項目如何使用此依賴項,其值可以是compile,test以及runtime。要想獲得可以指定的依賴項的更多信息,請參考《項目描述符參考》。

 

對於更多的依賴項機制,請參考《依賴項管理》。

 

通過此dependency信息,maven可以在構建項目時引用此依賴項。那麼,maven從哪兒引用此依賴項呢?Maven會去本地庫(默認位置:~/.m2/repository)中查找所有依賴項。在上一節,我們把我們項目的產品(my-app-1.0-SNAPSHOT.jar)安裝到了本地庫中,一旦安裝完成,其它項目就可以把此jar文件作爲一個依賴項引用:

<project>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-other-app</artifactId>

  ...

  <dependencies>

    ...

    <dependency>

      <groupId>com.mycompany.app</groupId>

      <artifactId>my-app</artifactId>

      <version>1.0-SNAPSHOT</version>

      <scope>compile</scope>

    </dependency>

  </dependencies>

</project>

 

Maven發現項目引用的依賴項在本地庫中不存在時,自動把它從遠程庫中下載到本地庫中。你可能已經注意到,當你構建第一個項目時,Maven下載了一些包(這些依賴項與構建項目時用到的插件有關)。默認情況下,Maven使用的遠程庫在http://www.ibiblio.org/maven2。當然,你也可以自己設置遠程庫(公司的中心庫),作爲ibiblio的替代或者補充。關於庫德更多信息,請參考《庫介紹》。

 

讓我們增加一個依賴項到我們的項目中,假設我們需要日誌功能,必須增加log4j作爲依賴項。首先,我們需要知道log4j的groupId,artifactId以及version。

 

我們可以通過瀏覽ibiblio來查看它,或者使用Google來搜索“site:www.ibiblio.org maven2 log4j”。這個搜索會顯示一個稱爲“/maven2/log4j/log4j”或者“/pub/packages/maven2/log4j/log4j”的目錄。在那個目錄中,有一個名爲maven-metadata.xml的文件,這裏是那個文件的內容:

<metadata>

  <groupId>log4j</groupId>

  <artifactId>log4j</artifactId>

  <version>1.1.3</version>

  <versioning>

    <versions>

      <version>1.1.3</version>

      <version>1.2.4</version>

      <version>1.2.5</version>

      <version>1.2.6</version>

      <version>1.2.7</version>

      <version>1.2.8</version>

      <version>1.2.11</version>

      <version>1.2.9</version>

      <version>1.2.12</version>

    </versions>

  </versioning>

</metadata>

 

我們從這個文件查看到log4j的groupId=log4j,artifactId=log4j。同時,我們可以看到有多個不同的版本可以選擇。現在,我們僅僅使用最新版本,1.2.12(某些maven-metadata.xml文件會指定哪個版本爲當前版本)。除了maven-metadata.xml文件,我們還可以看到對應版本的一組目錄,裏面放了相應版本的log4j包,以及pom.xml(指明log4j的依賴項),還有另一個maven-metadata.xml文件和各個文件的md5文件。

 

現在,我們知道了所需的信息,可以在我們的pom.xml增加依賴項了,如下所示:

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-app</artifactId>

  <packaging>jar</packaging>

  <version>1.0-SNAPSHOT</version>

  <name>Maven Quick Start Archetype</name>

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

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

    <dependency>

      <groupId>log4j</groupId>

      <artifactId>log4j</artifactId>

      <version>1.2.12</version>

      <scope>compile</scope>

    </dependency>

  </dependencies>

</project>

 

 

現在執行編譯項目(mvn compile)時,可以看到maven下載log4j。

MAVEN指南(3)

2.5.如何創建JAR以及把它安裝到本地庫中?

執行以下命令:

mvn package

如果你看以下項目的POM,你可以注意到packaging元素被設置爲jar。這讓maven知道從以上命令產生一個jar文件。在${basedir}/target目錄下,產生了一個jar文件。

 

現在,你想將產生的jar文件安裝到你的本地庫中(~/.m2/repository是默認的位置)。想了解庫的更多信息,請參考《庫介紹》。執行以下命令,就能安裝到本地庫:

mvn install

 

執行過程中會產生如下輸出:

[INFO] ----------------------------------------------------------------------------

[INFO] Building Maven Quick Start Archetype

[INFO]    task-segment: [install]

[INFO] ----------------------------------------------------------------------------

[INFO] [resources:resources]

[INFO] [compiler:compile]

Compiling 1 source file to <dir>/my-app/target/classes

[INFO] [resources:testResources]

[INFO] [compiler:testCompile]

Compiling 1 source file to <dir>/my-app/target/test-classes

[INFO] [surefire:test]

[INFO] Setting reports dir: <dir>/my-app/target/surefire-reports

 

-------------------------------------------------------

 T E S T S

-------------------------------------------------------

[surefire] Running com.mycompany.app.AppTest

[surefire] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.001 sec

 

Results :

[surefire] Tests run: 1, Failures: 0, Errors: 0

 

[INFO] [jar:jar]

[INFO] Building jar: <dir>/my-app/target/my-app-1.0-SNAPSHOT.jar

[INFO] [install:install]

[INFO] Installing <dir>/my-app/target/my-app-1.0-SNAPSHOT.jar to <local-repository>/com/mycompany/app/my-app/1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.jar

[INFO] ----------------------------------------------------------------------------

[INFO] BUILD SUCCESSFUL

[INFO] ----------------------------------------------------------------------------

[INFO] Total time: 5 seconds

[INFO] Finished at: Tue Oct 04 13:20:32 GMT-05:00 2005

[INFO] Final Memory: 3M/8M

[INFO] ----------------------------------------------------------------------------

 

 

注意執行測試的surefire插件,它會按命名規則查找所有的測試文件,默認情況下,測試文件包括:

Ø       **/*Test.java

Ø       **/Test*.java

Ø       **/*TestCase.jave

默認情況下,被排除的:

Ø       **/Abstract*Test.java

Ø       **/Abstract*TestCase.jave

 

到目前爲止,已經經歷了安裝、構建、測試、打包、安裝典型的maven項目等步驟。這可能是大多數項目使用maven需要經歷的步驟,而驅動的項目模型文件只有18行內容,對比典型的build文件,它的行數比pom多的多。

 

不需任何附加工作maven依靠此POM就可以爲你的項目產生一個網站,你只須定製你的maven網站,如果時間緊迫,你只須執行以下命令:

mvn site

 

還有許多goals可以執行,比如

mvn clean

此命令刪除target目錄。

 

可能你需要爲你的項目產生一個IntelliJ IDEA 描述符,執行以下命令:

mvn idea:idea

 

2.6.如何使用插件?

Maven 1.0用戶注意:在Maven 1.0中,你可能必須加入一些譬如preGoal到maven.xml中,以及project.properties的一些入口中。這裏有些不同,比如,我們配置java編譯器,以允許編譯jdk 5.0的源碼,這隻要簡單的在你的POM中加入:

.

<build>

  <plugins>

    <plugin>

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

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

      <configuration>

        <source>1.5</source>

        <target>1.5</target>

      </configuration>

    </plugin>

  </plugins>

</build>

.

.

 

 

maven2.0中,所有的插件看起來更像依賴項,並且某些方面確實就是依賴項。這個插件(包含特定的版本,如果指定的話,否則使用最新版本)將被自動下載並使用。

 

Configuration元素用來對編譯插件的每個goal提供參數。具體請參考《插件列表》、《構建生命週期介紹》。

 

2.7.如何在jar文件中加入資源?

在示例應用程序中,增加目錄${basedir}/src/main/resources,我們把資源文件放入此目錄。任何在${basedir}/src/main/resources目錄中的文件和目錄都將被打包到jar文件中。

my-app

|-- pom.xml

`-- src

    |-- main

    |   |-- java

    |   |   `-- com

    |   |       `-- mycompany

    |   |           `-- app

    |   |               `-- App.java

    |   `-- resources

    |       `-- META-INF

    |           `-- application.properties

    `-- test

        `-- java

            `-- com

                `-- mycompany

                    `-- app

                        `-- AppTest.java

 

 

在這個例子中,我們在${basedir}/src/main/resources目錄下放了一個META-INF目錄並在META-INF目錄中放了一個application.properties文件。如果你將jar文件解壓,可以看到以下內容:

|-- META-INF

|   |-- MANIFEST.MF

|   |-- application.properties

|   `-- maven

|       `-- com.mycompany.app

|           `-- my-app

|               |-- pom.properties

|               `-- pom.xml

`-- com

    `-- mycompany

        `-- app

            `-- App.class

 

 

就像你看到的那樣,${basedir}/src/main/resources中的內容在jar文件的起始位置,我們的application.properties文件在META-INF目錄下。同時,一些其他文件如META-INF/MANIFEST.MF,以及pom.xml和pom.properties文件也在其中,對於maven產生的jar文件來說,這是maven的標準行爲。你可以自行創建自己的manifest,不過如果你不指定,maven會產生一個默認的。由於pom.xml和pom.properties文件都被打包到jar文件中,所以maven產生的產品都是自描述的,一個簡單的應用就是獲得應用程序版本。打開POM文件可能需要一些maven的工具,但打開屬性文件可以使用標準的java API來做到,屬性文件pom.properties如下所示:

#Generated by Maven

#Tue Oct 04 15:43:21 GMT-05:00 2005

version=1.0-SNAPSHOT

groupId=com.mycompany.app

artifactId=my-app

 

 

爲了單元測試,可能需要把資源加入到classpath,你可以遵照同樣的模式:

my-app

|-- pom.xml

`-- src

    |-- main

    |   |-- java

    |   |   `-- com

    |   |       `-- mycompany

    |   |           `-- app

    |   |               `-- App.java

    |   `-- resources

    |       `-- META-INF

    |           |-- application.properties

    `-- test

        |-- java

        |   `-- com

        |       `-- mycompany

        |           `-- app

        |               `-- AppTest.java

        `-- resources

            `-- test.properties

 

那麼在測試代碼中,只須使用如下代碼就可訪問這些資源:

...

 

// Retrieve resource

InputStream is = getClass().getResourceAsStream( "/test.properties" );

 

// Do something with the resource

 

...

 

 

 

開始使用Maven

2.1.Maven是什麼?

Maven本質上是一個項目管理工具,Maven提供一下特性來提供項目管理:

Ø       構建

Ø       文檔

Ø       報表

Ø       依賴(相關性)

Ø       SCMs

Ø       發佈

Ø       分發

Maven不只是一個項目構建工具,並且也不只是ant的一個替代品。Maven是和ant完全不同的一個東西。Ant僅僅是一個簡單的跨平臺的構建工具,而Maven是一個模式應用,爲了達到可視性、複用性、維護性和易於理解的一個下部構造(Maven is about the application of patterns in order to acheive an infrastructure which displays the characteristics of visibility, reusability, maintainability, and comprehensibility.)。

 

2.2.如何開始你的第一個Maven項目

這裏要使用Maven的achetype機制,一個achetype被定義成一個原始的模式或者模型。在Maven裏,archetype是一個項目的模板,通過這個模板,再加上一些用戶的輸入就產生了一個可以工作的、符合用戶需要的Maven項目。

 

下面開始創建第一個項目,執行一下命令行:

Mvn archetype:create –DgroupId=com.mycompany.app –DartifactId=my-app

一旦執行了以上命令,你會發現maven爲這個新項目創建了一個名爲my-app的目錄,同時此目錄中有一個pom.xml文件,文件內容如下所示:

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>

  <artifactId>my-app</artifactId>

  <packaging>jar</packaging>

  <version>1.0-SNAPSHOT</version>

  <name>Maven Quick Start Archetype</name>

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

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

</project>

 

Pom.xml包含項目對象模型(POM)。POM是Maven的基本單元,記住,Maven是以項目爲中心的,所有的東西都圍繞項目展開。簡而言之,POM包含項目的所有重要信息,並且本質上提供了一站式的項目信息。關於pom的詳細介紹,請參考《POM介紹》。

下面是pom中的一些重要元素:

Ø       projectpom.xml文件中的頂層元素;

Ø       modelVersion:指明POM使用的對象模型的版本。這個值很少改動。

Ø       groupId:指明創建項目的組織或者小組的唯一標識。GroupId是項目的關鍵標識,典型的,此標識以組織的完全限定名來定義。比如,org.apache.maven.plugins是所有Maven插件項目指定的groupId。

Ø       artifactId:指明此項目產生的主要產品的基本名稱。項目的主要產品通常爲一個JAR文件。第二,象源代碼包通常使用artifactId作爲最後名稱的一部分。典型的產品名稱使用這個格式:<artifactId>-<version>.<extension>(比如:myapp-1.0.jar)。

Ø       version:項目產品的版本號。Maven幫助你管理版本,可以經常看到SNAPSHOT這個版本,表明項目處於開發階段。

Ø       name:項目的顯示名稱,通常用於maven產生的文檔中。

Ø       url:指定項目站點,通常用於maven產生的文檔中。

Ø       description:描述此項目,通常用於maven產生的文檔中。

 

POM中所有元素的說明,請參考《POM參考》。

 

產生了第一個項目的archetype後,你可以發現maven爲你創建瞭如下的目錄結構:

my-app

|-- pom.xml

`-- src

    |-- main

    |   `-- java

    |       `-- com

    |           `-- mycompany

    |               `-- app

    |                   `-- App.java

    `-- test

        `-- java

            `-- com

                `-- mycompany

                    `-- app

                        `-- AppTest.java

 

 

 

archetype產生的項目有一個POM,一個源代碼樹,以及一個測試代碼樹,這是maven項目的標準佈局(應用程序源碼位於${basedir}/src/main/java,而測試源碼位於${basedir}/src/test/java,這裏${basedir}代表包含pom.xml的根目錄)。

 

如果你想改變這個默認佈局,請參考《標準目錄佈局介紹》。

 

2.3.如何編譯應用程序源碼?

執行一下命令編譯應用程序源碼:

mvn compile

當執行此命令的時候,可以看到以下信息:

[INFO] ----------------------------------------------------------------------------

[INFO] Building Maven Quick Start Archetype

[INFO]    task-segment: [compile]

[INFO] ----------------------------------------------------------------------------

[INFO] artifact org.apache.maven.plugins:maven-resources-plugin: checking for updates from central

...

[INFO] artifact org.apache.maven.plugins:maven-compiler-plugin: checking for updates from central

...

[INFO] [resources:resources]

...

[INFO] [compiler:compile]

Compiling 1 source file to <dir>/my-app/target/classes

[INFO] ----------------------------------------------------------------------------

[INFO] BUILD SUCCESSFUL

[INFO] ----------------------------------------------------------------------------

[INFO] Total time: 3 minutes 54 seconds

[INFO] Finished at: Fri Sep 23 15:48:34 GMT-05:00 2005

[INFO] Final Memory: 2M/6M

[INFO] ----------------------------------------------------------------------------

 

 

第一次執行此命令(或者其他命令)時,maven需要下載所有插件以及滿足此命令的依賴項。對於一個乾淨的maven安裝版本,這需要花費一點時間。如果你再次運行此命令,maven就無需下載新的插件和依賴項了。

 

就像你從輸出中看到的那樣,編譯過的類文件被存放到${basedir}/target/classes目錄中,這個也是Maven標準的目錄佈局。

 

2.4.如何編譯測試源碼和運行單元測試?

運行一下命令:

mvn test

 

運行過程中會有以下輸出:

[INFO] ----------------------------------------------------------------------------

[INFO] Building Maven Quick Start Archetype

[INFO]    task-segment: [test]

[INFO] ----------------------------------------------------------------------------

[INFO] artifact org.apache.maven.plugins:maven-surefire-plugin: checking for updates from central

...

[INFO] [resources:resources]

[INFO] [compiler:compile]

[INFO] Nothing to compile - all classes are up to date

[INFO] [resources:testResources]

[INFO] [compiler:testCompile]

Compiling 1 source file to C:/Test/Maven2/test/my-app/target/test-classes

...

[INFO] [surefire:test]

[INFO] Setting reports dir: C:/Test/Maven2/test/my-app/target/surefire-reports

 

-------------------------------------------------------

 T E S T S

-------------------------------------------------------

[surefire] Running com.mycompany.app.AppTest

[surefire] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0 sec

 

Results :

[surefire] Tests run: 1, Failures: 0, Errors: 0

 

[INFO] ----------------------------------------------------------------------------

[INFO] BUILD SUCCESSFUL

[INFO] ----------------------------------------------------------------------------

[INFO] Total time: 15 seconds

[INFO] Finished at: Thu Oct 06 08:12:17 MDT 2005

[INFO] Final Memory: 2M/8M

[INFO] ----------------------------------------------------------------------------

 

輸出中,有些內容值得注意:

Ø       這個時候,maven會下載更多的依賴項。這些依賴項和插件是運行測試時所需要的。

Ø       在編譯和執行測試之前,maven按需編譯main代碼

 

如果你只須編譯測試代碼(無需運行測試),執行以下代碼:

mvn test-compile

 

MAVEN指南(1)

1.下載並安裝

目前的版本爲2.0.2,從http://maven.apache.org下載合適的分發包,

 

系統需求:

Jdk

1.4+

內存

 

磁盤空間

大概100M

操作系統

 

 

 

安裝:

Windows2000/XP下:

Ø       解壓maven-2.0.2-bin.zip到相應的安裝目錄,以下假設目錄爲C:/Program Files/Apache Software Foundation/maven-2.0.2。

Ø       設置環境變量M2_HOME= C:/Program Files/Apache Software Foundation/maven-2.0.2,同時,將MAVEN的bin路徑加到path環境變量中,PATH=%PATH%;%M2_HOME%/bin

Ø       運行mvn --version,來驗證安裝。

 

Unix系列操作系統下(Linux, Solaris and Mac OS X):

Ø       將分發包解壓到安裝路徑下,假設爲/usr/local/maven-2.0.2

Ø       bin目錄加入到path環境變量,比如:export PATH=/usr/local/maven-2.0.2y/bin:$PATH

Ø       運行mvn –version來驗證安裝。

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