子產品拆分是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項目部署到伺服器中就可以正常啟動和調試。
作者:邴越
掃碼關注公衆号:架構進化論,獲得第一手的技術資訊和原創文章
如果文章對您有幫助,可以點選文章右下角【推薦】一下,您的鼓勵是作者堅持原創和持續寫作的最大動力!