1. 程式人生 > >Maven搭建spring boot多模組專案打jar war zip 包方式

Maven搭建spring boot多模組專案打jar war zip 包方式

Spring boot 父專案聚合以下模組,下圖是parent.pom:


其中controller是web模組,各個模組的依賴關係如下:


由於spring boot 內嵌了servlet容器,而且提供了專案的java -jar啟動方式,所以可以把所有模組都打為jar包形式:

controller模組打jar包pom如下:


打包後直接在target目錄下找到cms-controller.jar,此處開啟命令列視窗執行java -jar cms-controller.jar 專案就啟動了。

接下來是war包的打包方式:

如果我們想要將web模組打包為可以在Servlet容器中部署的war包的話,就不能依賴於CmsApplication的main啟動類了,而是要以類似於web.xml檔案配置的方式來啟動Spring應用上下文,我們可以宣告這樣一個類:

public class ApplicationXml extends SpringBootServletInitializer {  
    @Override  
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {  
        return application.sources(CmsApplication.class);  
    }  

}  

宣告這個類之後就無須在編寫額外的Web.xml檔案了

接下來把cms-controller的pom檔案的packaging方式改為war,還需要加上以下配置:


<!-- 這裡排除掉內建的tomcat依賴,不然專案啟動會出錯 -->


這樣打war包就可以部署到tomcat容器運行了,其他模組會以jar包的形式打包在lib目錄下,這裡需要注意的是tomcat的版本一定要在7.0.42以上。

接下來是打zip包的形式,我們的需求是除了將專案必須的檔案打包進去後還要將一些說明文件打包進去:這裡我們以doc目錄下的兩個bat檔案作為演示:


首先我們加入打zip包所需的外掛:

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2.1</version>
                <configuration>
                    <descriptors>

                        <descriptor>src/main/resources/buildzip.xml</descriptor>

                        <!--對應在src/main/resource包下建立buildzip.xml配置檔案-->

                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>

            </plugin>

buildzip檔案內容如下:

<assembly>
    <id>doc</id>
    <formats>
        <format>zip</format>
    </formats>
    <fileSets>
        <fileSet>  <!--將doc目錄下的所有檔案打包到zip包下doc目錄下-->
            <directory>doc</directory>
            <includes>
                <include>*.*</include>
            </includes>
            <outputDirectory>doc/</outputDirectory>
        </fileSet>
        <fileSet>  <!--將專案必須的檔案打包到zip包根目錄下-->
            <directory>${project.build.directory}/${project.build.finalName}</directory>
            <includes>  
                <include>**</include>  
            </includes>     
            <outputDirectory>/</outputDirectory>
        </fileSet>
    </fileSets>

</assembly>

這樣我們執行maven clean package 命令,zip包便打好了,我們看一看目錄結構:


這裡doc目錄下就是我們要放的額外文件,其他目錄是和打war包的內容一樣,我們把zip包複製到tomcat的webapp目錄下,因為tomcat只能自動解壓war包,所以我們需要手動解壓到當前目錄,執行tomcat,專案也成功啟動了。