Maven管理多模塊項目


 首先,我們要明確的多模塊項目的含義,它是指一個應用中包含多個module。一般來說,一個應用單獨部署成服務,只是打包的時候,maven會把各個module組合在一起。各模塊一般單獨打成jar放到lib目錄中,當然web應用也生成war包。 

   這里說的多模塊項目要與那種單獨自立門戶的多個application區分開來,多個application也可能有包級的關聯,但是它們各自分開了,不屬於多模塊項目的范疇。 

   maven對多模塊項目的管理大概是這樣的,它存在一個parent模塊,但實際沒有程序代碼,只包含一個pom.xml,該pom是用來給子模塊來引用的。 
   目錄結構與下面的類似: 
    simple-parent 
    +-simple-weather 
         +-src 
         +-target 
         \-pom.xml 
    +-simple-webapp 
         +-src 
         +-target 
         \-pom.xml 
    \-pom.xml 
在這個目錄結構中,一個父模塊包含了兩個子模塊。 
各個pom.xml的內容大致如下: 
pom.xml: 

Xml代碼   收藏代碼
  1.  <modules>  
  2. <groupId>org.sonatype.mavenbook.multi</groupId>   
  3.  <artifactId>parent</artifactId>   
  4.  <version>0.8-SNAPSHOT</version>   
  5.  <packaging>pom</packaging>   
  6.  <module>simple-weather</module>   
  7.  <module>simple-webapp</module>   
  8.  </modules>  
  9. <dependencies>  
  10.  <dependency>  
  11.  <groupId>velocity</groupId>   
  12.  <artifactId>velocity</artifactId>   
  13.  <version>1.5</version>   
  14.  </dependency>  
  15.  </dependencies>  


simple-weather/pom.xml: 
 

Xml代碼   收藏代碼
  1. <parent>  
  2.   <groupId>org.sonatype.mavenbook.multi</groupId>   
  3.   <artifactId>simple-parent</artifactId>   
  4.   <version>0.8-SNAPSHOT</version>   
  5.   </parent>  
  6.  <dependencies>  
  7.  <dependency>  
  8.   <groupId>junit</groupId>   
  9.   <artifactId>junit</artifactId>   
  10.   <version>3.8.1</version>   
  11.   <scope>test</scope>   
  12.   </dependency>  
  13.   </dependencies>  


simple-webapp/pom.xml: 

Xml代碼   收藏代碼
  1. <parent>  
  2.  <groupId>org.sonatype.mavenbook.multi</groupId>   
  3.  <artifactId>simple-parent</artifactId>   
  4.  <version>0.8-SNAPSHOT</version>   
  5.  </parent>  
  6. <dependencies>  
  7. <dependency>  
  8.  <groupId>org.apache.geronimo.specs</groupId>   
  9.  <artifactId>geronimo-servlet_2.4_spec</artifactId>   
  10.  <version>1.1.1</version>   
  11.  </dependency>  
  12.  </dependencies>  



如果按父pom.xml打包,會輸出 simple-weather**.jar,simple-webapp**.war兩個包; 
如果按simple-weather/pom.xml打包,則只會輸出 simple-weather**.jar; 
如果按simple-webapp/pom.xml打包,則只會輸出 simple-webapp**.war。 

另外,子模塊會繼承父模塊的包依賴,使用mvn dependency:tree可以查看各個模塊的包依賴列表,simple-weather,simple-webapp項目都有引用到 velocity包。 

雖然這是一個application下包含了多個module的結構,但是在eclipse中,還是得對每個子module單獨建project來管理源碼。具體可以分別在simple-weather、simple-webapp目錄下使用mvn eclipse:eclipse來創建eclipse project,創建完畢后,你就可以在文件.classpath中看到,包依賴關系已經按照pom.xml中的配置自動生成了。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM