使用Maven进行多模块拆分

模块拆分是Maven经常使用的功能,简单梳理一下如何使用Maven进行多模块拆分,

只做归纳总结,网上资料很多,不再一步一步实际创建和部署。

建立Maven多模块项目

一个简单的Java Web项目,Maven模块结构是这样的:

上述示意图中,有一个父项目(parent)聚合很多子项目(mytest-controller,mytest-util, mytest-dao, mytest-service, mytest-web)。每个项目,不管是父子,都含有一个pom.xml文件。而且要注意的是,小括号中标出了每个项目的打包类型。父项目是pom,也只能是pom。子项目有jar,或者war。根据它包含的内容具体考虑。

父项目声明打包类型等:

<groupId>my.test</groupId>
<artifactId>mytest-parent</artifactId>
<version>1.0</version>
<packaging>pom</packaging>

 


声明各个子模块:

<modules>
        <module>mytest-controller</module>
        <module>mytest-service</module>
		<module>mytest-util</module>
		<module>mytest-dao</module>
		<module>mytest-web-1</module>
		<module>mytest-web-2</module>
</modules>

 

然后在子模块中,声明父工程,子模块中代码如下:

<parent>
		<groupId>my.test</groupId>
		<artifactId>mytest-util</artifactId>
		<version>1.0</version>
</parent>

一般来说,项目中需要的外部依赖等都在父项目中引入,这样在子项目中省去了不必要的配置。

另外,各个子项目间的依赖在单独的pom.xml中配置,
比如mytest-web项目依赖控制层的mytest-controller,那么就在依赖中单独配置

<dependency>
			<groupId>my.test<</groupId>
			<artifactId>mytest-controller</artifactId>
			<version>1.0</version>
</dependency>

这就需要在项目拆分和架构之前需要理清各个模块间的依赖关系。

在最后的Web模块如何打包

如果是单个War项目,使用普通的构建方式即可,需要注意的是如果项目中包含多个war的子模块,

需要使用maven的maven-war-plugin插件的overlays属性来处理,最终主web项目pom.

<build>
		<finalName>xhcms</finalName>
		<plugins>
		    <!-- 合并多个war -->  
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<overlays>
						<overlay>
							<groupId>my.test</groupId>
							<artifactId>my-test-web-1</artifactId>
							<excludes>
								<exclude>WEB-INF/web.xml</exclude>
							</excludes>
							<!-- 目标路径 -->
							<targetPath>test</targetPath>
						</overlay>
					</overlays>
				</configuration>
			</plugin>
		</plugins>
	</build>

  

如何在IDE中启动和调试

如果项目配置正确,那么直接使用Eclipse的server插件,把最后的web项目部署到服务器中就可以正常启动和调试。

 

posted @ 2015-09-20 22:01  邴越  阅读(8165)  评论(0编辑  收藏  举报