# SpringBoot3教程 - 22 项目打包部署

SpringBoot 项目一般是打成jar包,然后运行jar包即可,jar包中内置了服务器,默认是Tomcat。

我们可以使用考虑使用 docker 部署 SpringBoot 项目,关于 Docker 的知识,可以学习本站的 Docker教程 (opens new window)

# 22.1 打jar包

首先要在要打包的模块的 pom.xml 文件中引入 spring-boot-maven-plugin 插件。

<build>
    <plugins>
        <!-- 用于打包 -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
                    </goals>
                </execution>
            </executions>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

在 IDEA 右侧的 Maven 窗口,找到 package 操作,双击打包。

执行完成,会在模块的 target 目录下生成对应的项目 jar 包。

# 22.2 部署

有了 jar 包就可以 java -jar 运行了,但是如果我们通过 SSH 远程到服务器来运行,直接使用 java -jar 运行,当断开 SSH 连接的时候,服务也就停止了,因为直接使用 java -jar 运行,服务是在前端运行的,所以我们需要使用方法让服务在后端运行。

使用如下命令:

nohup java -jar doubi-api.jar > ./logs/doubi-api-console.log 2>&1 &

# 也可以指定配置文件
nohup java -jar doubi-api.jar --spring.profiles.active=test > ./logs/doubi-api-console.log 2>&1 &
# 或者
nohup java -jar -Dspring.profiles.active=test doubi-api.jar > ./logs/doubi-api-console.log 2>&1 &
1
2
3
4
5
6
  • nohupnohup 命令用来忽略挂起(HUP)信号。它允许命令在用户退出或关闭终端后继续运行。
  • > ./logs/doubi-api-console.log:程序运行期间产生的日志输出会被写入这个文件;
  • 2>&1:表示将标准错误(stderr)重定向到标准输出(stdout)。也就是说,程序运行期间产生的错误信息也会被写入到 doubi-api-console.log 文件中。
  • &:这个符号表示在后台运行命令,而不需要等待该命令执行完成。
  • --spring.profiles.active=test:这部分是直接传递给 Spring Boot 应用的参数,用于指定 Spring 配置文件为 test
  • -Dspring.profiles.active=test:这部分是传递给 JVM 的系统属性,Spring Boot 会读取此属性并设置相应的配置文件为 test

# 22.3 docker部署

参见 Docker部署SpringBoot项目 (opens new window)