1 创建模板项目
浏览器访问「start.spring.io」,使用 Spring Initializr 来创建一个 Spring Boot Web 项目。
本文的选项如下:
- Project 选择 Maven
- Language 选择 Java
- Spring Boot 选择 3.1.0
- Packaging 选择 Jar
- Java 选择 17
- Dependencies 勾选 Spring Web
选好以后,点击「Generate」按钮即可以生成项目模板,将 zip 包下载到本地,解压以后即可以使用 IDE 打开了。
打开以后,可以看到该模板工程的项目结构:
text
代码解读
复制代码
demo ├─ src/main/java │ └─ com.example.demo │ └─ DemoApplication.java └─ pom.xml
2 添加代码
下面,将src/main/java/com/example/demo
文件夹下的DemoApplication.java
文件内容替换为如下内容:
java
代码解读
复制代码
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @GetMapping("/hello") public String hello(@RequestParam(value = "name", defaultValue = "World") String name) { return String.format("Hello %s!", name); } }
这就是使用 Spring Boot 搭建一个「Hello World!」Web 服务的全部代码。
下面解释一下用到的几个注解:
@RestController
告诉 Spring 当前类提供了一个 Web 访问端点;@GetMapping("/hello")
告诉 Spring 使用hello()
方法来响应发送至http://localhost:8080/hello
的请求;@RequestParam
告诉 Spring 可在请求中为name
参数传值(不传的话使用默认值World
)。
3 进行测试
下面,使用 Maven 构建并运行程序。
打开命令行,进入程序根目录,然后使用如下 Maven 命令打包及运行程序:
shell
代码解读
复制代码
mvn clean package mvn spring-boot:run --quiet
程序启动完成后,使用如下 CURL 命令进行测试:
shell
代码解读
复制代码
curl http://localhost:8080/hello Hello World!
shell
代码解读
复制代码
curl 'http://localhost:8080/hello?name=Larry' Hello Larry!
综上,本文完成了对 Spring Boot 项目的快速搭建,可以看到 Spring Boot 项目非常的简单易用。本文涉及的完整项目代码已托管至「GitHub」,欢迎关注或 Fork。
文章评论