新建项目rest-service
Intellij IDEA ,新建项目Maven
空项目,目录如下:
配置POM文件
<?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.springtest</groupId>
<artifactId>rest-service</artifactId>
<version>1.0-SNAPSHOT</version>
<name>rest-service Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.1</version>
</parent>
<!-- Additional lines to be added here... -->
</project>>
添加依赖
<!-- Additional lines to be added here... -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
等待依赖包下载完毕。项目新建完成
Hello World
@RestController
@EnableAutoConfiguration
public class MyApplication {
@RequestMapping("/")
String home() {
return "Hello world!";
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
运行 'Run MyApplication'
,打开网页,输入地址:localhost:8080,返回:
Hello world!
生成jar包
生产环境部署、运行还是需要jar包的
<!-- Additional lines to be added here... -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
运行 'mvn package'
,命令行打印,jar包会出现在项目下的target
文件夹
…
[INFO] — maven-jar-plugin:3.2.0:jar (default-jar) @ rest-service —
[INFO] Building jar: /Users/guxianxiong/springtest/rest-service/target/rest-service-1.0-SNAPSHOT.jar
[INFO]
[INFO] — spring-boot-maven-plugin:2.6.1:repackage (repackage) @ rest-service —
[INFO] Replacing main artifact with repackaged archive
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.026 s
[INFO] Finished at: 2021-12-07T15:18:08+08:00
[INFO] ------------------------------------------------------------------------
项目目录下,运行项目
$ java -jar target/rest-service-1.0-SNAPSHOT.jar
# ctrl + c 结束应用