Maven学习记录4——Maven管理多模块项目

来源:互联网 发布:linux 用代码链接网络 编辑:程序博客网 时间:2024/06/06 15:56
 首先,我们要明确的多模块项目的含义,它是指一个应用中包含多个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中的配置自动生成了。
0 0
原创粉丝点击