且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Maven使用笔记(六)使用Maven进行多模块拆分

更新时间:2022-09-12 23:37:23

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

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

建立Maven多模块项目

一个简单的Java Web项目,Maven模块结构是这样的:
Maven使用笔记(六)使用Maven进行多模块拆分

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

父项目声明打包类型等:

1
2
3
4
<groupId>my.test</groupId>
<artifactId>mytest-parent</artifactId>
<version>1.0</version>
<packaging>pom</packaging>

 


声明各个子模块:

1
2
3
4
5
6
7
8
<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>

 

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

1
2
3
4
5
<parent>
        <groupId>my.test</groupId>
        <artifactId>mytest-util</artifactId>
        <version>1.0</version>
</parent>

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

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

1
2
3
4
5
<dependency>
            <groupId>my.test<</groupId>
            <artifactId>mytest-controller</artifactId>
            <version>1.0</version>
</dependency>

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

在最后的Web模块如何打包

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<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项目部署到服务器中就可以正常启动和调试。

 


本文转自邴越博客园博客,原文链接:http://www.cnblogs.com/binyue/p/4800934.html,如需转载请自行联系原作者