在项目部署中,可以把spring boot项目打jar包部署,将前台html、js等资源也打入jar包内,启动jar就启动整个项目,本文用的spring boot版本是2.0.4。其实只需在pom.xml中plugin部分配置下。
-
新建了一个测试项目,目录结构如下:
-
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>package</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>package</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>demo</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.example.PackageApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
"<packaging>jar</packaging>"指定为jar, “<finalName>demo</finalName>”是jar包名称,“<mainClass>com.example.PackageApplication</mainClass>”指定启动类。所有的pom.xml只修改了"<plugin>...</plugin>"中的内容。
-
两个测试页面:
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<h1>spring boot.</h1>
</body>
</html>
<!--test.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<h1>test.html</h1>
</body>
</html>
-
打包:
在打包前可以"clean"下,然后在"package"。成功后结果输出:
target目录下的demo.jar就是最终的运行文件。
-
运行:
终端进入demo.jar所在目录
可以在当前目录下的application.properties(或者config目录下)中配置属性,启动时会覆盖jar包中resources下的application.properties中相同属性。在这我只设置了一个端口"server.port=8082"。执行"java -jar demo.jar"命令即可启动项目。浏览器输入"http://localhost:8082/"或"http://localhost:8082/test.html"得到页面内容。