快速入门
本章将通过一个完整的示例,带你快速上手 Spring Boot,创建一个简单的 RESTful API。
创建项目
使用 Spring Initializr
-
配置如下:
- Project: Maven
- Language: Java
- Spring Boot: 3.2.x(选择最新稳定版)
- Group: com.example
- Artifact: hello-spring-boot
- Name: hello-spring-boot
- Package name: com.example.hello
- Packaging: Jar
- Java: 17
-
添加依赖:
- Spring Web:用于构建 Web 应用和 RESTful API
-
点击 GENERATE 下载项目
项目文件结构
解压后的项目结构:
hello-spring-boot/
├── src/
│ ├── main/
│ │ ├── java/com/example/hello/
│ │ │ └── HelloSpringBootApplication.java
│ │ └── resources/
│ │ ├── static/
│ │ ├── templates/
│ │ └── application.properties
│ └── test/java/com/example/hello/
│ └── HelloSpringBootApplicationTests.java
├── pom.xml
├── mvnw
├── mvnw.cmd
└── HELP.md
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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 继承 Spring Boot 父项目 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<!-- 项目坐标 -->
<groupId>com.example</groupId>
<artifactId>hello-spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hello-spring-boot</name>
<!-- Java 版本 -->
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<!-- Spring Web 起步依赖 -->
<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>
<plugins>
<!-- Spring Boot Maven 插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
关键配置说明:
| 元素 | 说明 |
|---|---|
spring-boot-starter-parent | 继承 Spring Boot 默认配置,包括依赖版本管理 |
spring-boot-starter-web | 包含 Spring MVC、Tomcat、Jackson 等 Web 开发所需依赖 |
spring-boot-maven-plugin | 支持打包可执行 JAR 文件 |
主启动类
打开 HelloSpringBootApplication.java:
package com.example.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(HelloSpringBootApplication.class, args);
}
}
@SpringBootApplication 注解解析
@SpringBootApplication 是一个组合注解,等价于:
@SpringBootConfiguration // 标识这是一个配置类
@EnableAutoConfiguration // 启用自动配置
@ComponentScan // 启用组件扫描
public class HelloSpringBootApplication {
// ...
}
各注解作用:
| 注解 | 作用 |
|---|---|
@SpringBootConfiguration | 表明这是一个配置类,等同于 @Configuration |
@EnableAutoConfiguration | 根据 classpath 自动配置 Spring 应用 |
@ComponentScan | 扫描当前包及子包中的 @Component、@Service、@Repository 等 |
扫描范围
默认情况下,Spring Boot 只扫描主启动类所在包及其子包:
com.example.hello ← 主启动类所在包(扫描起点)
├── HelloSpringBootApplication.java
├── controller/ ← 会被扫描
│ └── HelloController.java
├── service/ ← 会被扫描
│ └── HelloService.java
└── model/ ← 会被扫描
└── User.java
com.example.other ← 不会被扫描(不在主包下)
└── OtherService.java
自定义扫描范围:
@SpringBootApplication(scanBasePackages = "com.example")
public class HelloSpringBootApplication {
// ...
}
创建 REST 控制器
在 com.example.hello.controller 包下创建 HelloController.java:
package com.example.hello.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class HelloController {
/**
* 简单的 Hello World 接口
*/
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
/**
* 带参数的 Hello 接口
* @param name 用户名
* @return 问候语
*/
@GetMapping("/greeting")
public String greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello, %s!", name);
}
/**
* 路径参数示例
* @param id 用户ID
* @return 用户信息
*/
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {
return "User ID: " + id;
}
}
注解详解
| 注解 | 作用 |
|---|---|
@RestController | 组合了 @Controller 和 @ResponseBody,方法的返回值直接作为 HTTP 响应体 |
@RequestMapping | 定义类级别的请求路径前缀 |
@GetMapping | 映射 HTTP GET 请求 |
@PostMapping | 映射 HTTP POST 请求 |
@PutMapping | 映射 HTTP PUT 请求 |
@DeleteMapping | 映射 HTTP DELETE 请求 |
@RequestParam | 绑定请求参数 |
@PathVariable | 绑定路径变量 |
@RequestBody | 绑定请求体(JSON) |
请求映射示例
@RestController
@RequestMapping("/api/users")
public class UserController {
// GET /api/users - 获取用户列表
@GetMapping
public List<User> list() {
return userService.findAll();
}
// GET /api/users/{id} - 获取单个用户
@GetMapping("/{id}")
public User get(@PathVariable Long id) {
return userService.findById(id);
}
// POST /api/users - 创建用户
@PostMapping
public User create(@RequestBody User user) {
return userService.save(user);
}
// PUT /api/users/{id} - 更新用户
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.save(user);
}
// DELETE /api/users/{id} - 删除用户
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userService.deleteById(id);
}
}
返回 JSON 数据
使用实体类
创建 User.java:
package com.example.hello.model;
public class User {
private Long id;
private String name;
private String email;
private Integer age;
// 构造方法
public User() {}
public User(Long id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
}
// Getter 和 Setter 方法
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
}
在控制器中返回对象:
@GetMapping("/user")
public User getUser() {
return new User(1L, "张三", "[email protected]", 25);
}
访问 http://localhost:8080/api/user,返回:
{
"id": 1,
"name": "张三",
"email": "[email protected]",
"age": 25
}
解释:Spring Boot 默认使用 Jackson 将对象序列化为 JSON,无需额外配置。
使用 Lombok 简化代码
添加 Lombok 依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
简化后的实体类:
package com.example.hello.model;
import lombok.*;
@Data // 生成 getter/setter/toString/equals/hashCode
@NoArgsConstructor // 生成无参构造方法
@AllArgsConstructor // 生成全参构造方法
public class User {
private Long id;
private String name;
private String email;
private Integer age;
}
运行与测试
启动应用
方式一:使用 Maven
# Windows
mvnw.cmd spring-boot:run
# macOS/Linux
./mvnw spring-boot:run
方式二:在 IDE 中运行
直接运行主启动类的 main 方法。
方式三:打包后运行
# 打包
./mvnw clean package
# 运行
java -jar target/hello-spring-boot-0.0.1-SNAPSHOT.jar
控制台输出
启动成功后,控制台显示:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.2.0)
2024-01-01 10:00:00.000 INFO 12345 --- [main] c.e.hello.HelloSpringBootApplication : Starting HelloSpringBootApplication
2024-01-01 10:00:00.000 INFO 12345 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2024-01-01 10:00:00.000 INFO 12345 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http)
2024-01-01 10:00:00.000 INFO 12345 --- [main] c.e.hello.HelloSpringBootApplication : Started HelloSpringBootApplication in 1.234 seconds
测试接口
使用浏览器:
直接访问 http://localhost:8080/api/hello
使用 curl:
# GET 请求
curl http://localhost:8080/api/hello
curl "http://localhost:8080/api/greeting?name=Spring"
# POST 请求
curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{"name":"李四","email":"[email protected]","age":30}'
使用 Postman / Apifox:
- 创建新请求
- 设置请求方法(GET/POST/PUT/DELETE)
- 输入 URL
- 发送请求并查看响应
配置文件
application.properties
# 服务器端口
server.port=8080
# 应用名称
spring.application.name=hello-spring-boot
# 开发环境配置(显示详细错误信息)
server.error.include-message=always
server.error.include-binding-errors=always
application.yml(推荐)
Spring Boot 也支持 YAML 格式的配置文件:
# 服务器配置
server:
port: 8080
error:
include-message: always
include-binding-errors: always
# 应用配置
spring:
application:
name: hello-spring-boot
YAML 格式优点:
- 层次结构清晰
- 支持复杂配置
- 避免重复前缀
多环境配置
创建不同环境的配置文件:
application.yml # 主配置
application-dev.yml # 开发环境
application-prod.yml # 生产环境
application-test.yml # 测试环境
激活指定环境:
# application.yml
spring:
profiles:
active: dev # 激活 dev 环境
或通过命令行参数:
java -jar app.jar --spring.profiles.active=prod
单元测试
Spring Boot 提供了完善的测试支持。
测试依赖
spring-boot-starter-test 已包含 JUnit 5、Mockito、AssertJ 等测试框架。
编写测试类
package com.example.hello.controller;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testHello() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Spring Boot!"));
}
@Test
void testGreeting() throws Exception {
mockMvc.perform(get("/api/greeting").param("name", "Spring"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Spring!"));
}
}
运行测试
# 运行所有测试
./mvnw test
# 运行指定测试类
./mvnw test -Dtest=HelloControllerTest
开发者工具
spring-boot-devtools 提供了开发时的便利功能。
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
主要功能
| 功能 | 说明 |
|---|---|
| 自动重启 | 类路径文件变化时自动重启应用 |
| LiveReload | 浏览器自动刷新 |
| 属性默认值 | 开发环境合理的默认配置 |
| 远程调试 | 支持远程应用调试 |
IDEA 配置自动重启
File→Settings→Build, Execution, Deployment→Compiler- 勾选
Build project automatically Settings→Advanced Settings- 勾选
Allow auto-make to start even if developed application is currently running
小结
本章我们学习了:
- 项目创建:使用 Spring Initializr 快速创建项目
- 主启动类:理解
@SpringBootApplication注解的作用 - REST 控制器:创建 RESTful API 接口
- JSON 响应:返回 JSON 格式数据
- 配置文件:使用 properties 和 yml 格式配置
- 运行测试:启动应用并测试接口
- 单元测试:编写和运行单元测试
- 开发者工具:使用 devtools 提高开发效率
练习
- 创建一个 Spring Boot 项目,添加 Spring Web 依赖
- 实现一个用户管理 API(增删改查)
- 为每个接口编写单元测试
- 配置多环境(dev、test、prod)
- 使用 devtools 实现热重载