概述
Spring Boot 是 Spring Framework 的一个扩展,旨在简化 Spring 应用程序的创建和开发过程。它提供了开箱即用的配置,使得开发者能够快速搭建基于Spring的应用程序,而不需要过多的配置。
Spring Boot整合Spring Web可以帮助开发者快速构建RESTful风格的Web应用,实现对资源的增删改查操作。
这种技术组合适用于需要快速搭建基于HTTP协议的RESTful风格的Web服务,例如前后端分离的应用、微服务架构中的服务提供方等场景。
主要依赖项配置
在 pom.xml
中添加以下依赖项:
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
true
实体类定义
使用 Lombok 简化【学生】实体类的编写:
package com.jkxiao.springbootweb;
import lombok.Data;
@Data
public class Student {
private Long id;
private String name;
private int age;
}
Controller类编写
package com.jkxiao.springbootweb;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;@RestController
@RequestMapping(“/students”)
public class StudentController {
private List students = new ArrayList<>();@GetMapping public List<student> getAllStudents() { return students; } /** * 根据id查询学生 * @param id * @return */ @GetMapping("/{id}") public Student getStudentByID(@PathVariable Long id) { return students.stream() .filter(student -> student.getId().equals(id)) .findFirst() .orElse(null); } /** * 创建学生 * @param student * @return */ @PostMapping public Student createStudent(@RequestBody Student student) { students.add(student); return student; } /** * 更新学生 * @param id * @param student * @return */ @PutMapping("/{id}") public Student updateStudent(@PathVariable Long id, @RequestBody Student student) { Student existingStudent = getStudentByID(id); if (existingStudent != null) { existingStudent.setName(student.getName()); existingStudent.setAge(student.getAge()); return existingStudent; } else { return null; } } /** * 删除学生 * @param id * @return */ @DeleteMapping("/{id}") public void deleteStudent(@PathVariable Long id) { students.removeIf(student -> student.getId().equals(id)); }
}
单元测试
package com.jkxiao.springbootweb;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@SpringBootTest
@AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class StudentControllerTest {@Autowired private MockMvc mockMvc; @Order(1) @Test void createStudent() throws Exception { String requestBody = "{\"id\":1,\"name\":jkxiao\",\"age\":20}"; mockMvc.perform(get("/students") .content(requestBody) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } @Order(2) @Test void getAllStudents() throws Exception { mockMvc.perform(get("/students")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } @Order(3) @Test void getStudentByID() throws Exception{ mockMvc.perform(get("/students/1")) .andExpect(status().isOk()); } @Order(4) @Test void updateStudent() throws Exception{ String requestBody = "{\"name\":\"xiao\",\"age\":20}"; mockMvc.perform(put("/students/1") .content(requestBody) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } @Order(5) @Test void deleteStudent() throws Exception{ mockMvc.perform(delete("/students/1")) .andExpect(status().isOk()); }
}
cURL 测试请求
- 获取所有学生信息:
curl http://localhost:8080/students
- 根据ID获取学生信息:
curl http://localhost:8080/students/1
- 创建学生:
curl -X POST -H "Content-Type: application/json" -d '{"id":1,"name":"jeiker","age":20}' http://localhost:8080/students
- 更新学生信息:
curl -X PUT -H "Content-Type: application/json" -d '{"id":1,"name":"jeikerxiao","age":25}' http://localhost:8080/students/1
- 删除学生:
curl -X DELETE http://localhost:8080/students/1
注意事项
- RESTful规范:接口设计应符合RESTful规范,使用HTTP方法(GET、POST、PUT、DELETE)进行资源的增删改查操作。当然,也可以只使用 (GET、POST)
- Lombok使用:在使用Lombok简化实体类编写时,需要在IDE中安装Lombok插件,并在项目中正确使用Lombok注解。
- 单元测试控制方法执行顺序:在单元测试类中,通过
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
和@Order(x)
注解来控制单元测试方法的执行顺序,标号小的执行优先级高。
这是一个从 https://juejin.cn/post/7368770335225692195 下的原始话题分离的讨论话题