Spring Boot 项目可以内嵌 Servlet 容器,因此部署极为方便,可直接打成可执行 JAR 包部署在有 Java 运行环境的服务器上,也可以像传统的 Java Web 应用程序那样打成 WAR 包运行。
JAR
使用 spring-boot-maven-plugin 插件可以创建一个可执行的 JAR 应用程序,前提是应用程序的 parent 为 spring-boot-starter-parent。配置方式如下:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
配置完成后,在当前项目的根目录下执行如下 Maven 命令进行打包:
mvn package
或者在 IntelliJ IDEA 中单击 Maven Project ,找到 Lifecycle 中的 package 双击打包。
打包成功后,在当前项目的根目录下找到 target 目录, target 目录中就有刚刚打成的 JAR 包:
boot-0.0.1-SNAPSHOT.jar
这种打包方式的前提是项目使用了 spring-boot-starter-parent 作为 parent,在大部分项目中,项目的 parent 可能并不是 spring-boot-starter-parent ,而是公司内部定义好的一个配置 ,此时 spring-boot-maven-plugin 插件并不能直接使用,需要多做一些额外配置 :
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.2.4.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
配置完成后,就可以通过 Maven 命令或者 IntelliJ IDEA 中的 Maven 插件进行打包,打包方式和前文一致。
运行:
java -jar boot-0.0.1-SNAPSHOT.jar &
注意,最后面的 & 表示让项目在后台运行。由于在生产环境中,Linux 大多数情况下都是远程服务器,开发者通过远程工具连接 Linux ,如果使用上面的命令启动 JAR,一旦窗口关闭, JAR 就停止运行了,因此一般通过如下命令启动 JAR:
nohup java -jar boot-0.0.1-SNAPSHOT.jar &
这里 nohup 表示当窗口关闭时服务不挂起,继续在后台运行。
WAR
在一些特殊情况下需要开发者将 Spring Boot 项目打成 WAR 包,然后使用传统的方式部署, 步骤如下:
修改 pom.xml 文件:
<package>war</package>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
提供 SpringBootServletInitializer 的子类,并覆盖其 configure 方法完成初始化操作,代码如下:
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import xyz.ther.boot.BootApplication;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder app) {
return app.sources(BootApplication.class);
}
}
经过以上配置后,接下来就可以对项目进行打包了。打包的方式和打 JAR 包的方式是一样的,打包成功后在 target 目录下生成一个 WAR 包,将该文件复制到 Tomcat 的 webapps 目录下,启动 Tomcat 即可。