Maven搭建spring boot多模块项目打jar war zip 包方式

Spring boot 父项目聚合以下模块,下图是parent.pom:

Maven搭建spring boot多模块项目打jar war zip 包方式

其中controller是web模块,各个模块的依赖关系如下:

Maven搭建spring boot多模块项目打jar war zip 包方式

由于spring boot 内嵌了servlet容器,而且提供了项目的java -jar启动方式,所以可以把所有模块都打为jar包形式:

controller模块打jar包pom如下:

Maven搭建spring boot多模块项目打jar war zip 包方式

打包后直接在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,还需要加上以下配置:

Maven搭建spring boot多模块项目打jar war zip 包方式

<!-- 这里排除掉内置的tomcat依赖,不然项目启动会出错 -->


这样打war包就可以部署到tomcat容器运行了,其他模块会以jar包的形式打包在lib目录下,这里需要注意的是tomcat的版本一定要在7.0.42以上。

接下来是打zip包的形式,我们的需求是除了将项目必须的文件打包进去后还要将一些说明文档打包进去:这里我们以doc目录下的两个bat文件作为演示:

Maven搭建spring boot多模块项目打jar war zip 包方式

首先我们加入打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包便打好了,我们看一看目录结构:

Maven搭建spring boot多模块项目打jar war zip 包方式

这里doc目录下就是我们要放的额外文档,其他目录是和打war包的内容一样,我们把zip包复制到tomcat的webapp目录下,因为tomcat只能自动解压war包,所以我们需要手动解压到当前目录,运行tomcat,项目也成功启动了。