模塊拆分是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項目部署到服務器中就可以正常啟動和調試。