feat(v1): unify API response, validation, exception handling and tests

This commit is contained in:
likingcode
2026-03-08 14:40:30 +00:00
parent 539dc41868
commit 6a4c6a369a
10 changed files with 216 additions and 73 deletions

View File

@@ -38,6 +38,12 @@
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
</dependency> </dependency>
<!-- 参数校验 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- 测试 --> <!-- 测试 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>

View File

@@ -0,0 +1,22 @@
package com.example.demo.common;
import java.time.Instant;
public record ApiResponse<T>(
int code,
String message,
T data,
Instant timestamp
) {
public static <T> ApiResponse<T> ok(T data) {
return new ApiResponse<>(0, "success", data, Instant.now());
}
public static <T> ApiResponse<T> ok(String message, T data) {
return new ApiResponse<>(0, message, data, Instant.now());
}
public static ApiResponse<Void> fail(int code, String message) {
return new ApiResponse<>(code, message, null, Instant.now());
}
}

View File

@@ -6,7 +6,6 @@ import com.example.demo.aop.RateLimited;
import com.example.demo.event.UserEventPublisher; import com.example.demo.event.UserEventPublisher;
import com.example.demo.model.User; import com.example.demo.model.User;
import com.example.demo.service.UserService; import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.HashMap; import java.util.HashMap;
@@ -20,17 +19,20 @@ import java.util.Map;
@RequestMapping("/aop") @RequestMapping("/aop")
public class AopEventController { public class AopEventController {
@Autowired private final UserService userService;
private UserService userService; private final UserEventPublisher eventPublisher;
private final PerformanceAspect performanceAspect;
private final RateLimitAspect rateLimitAspect;
@Autowired public AopEventController(UserService userService,
private UserEventPublisher eventPublisher; UserEventPublisher eventPublisher,
PerformanceAspect performanceAspect,
@Autowired RateLimitAspect rateLimitAspect) {
private PerformanceAspect performanceAspect; this.userService = userService;
this.eventPublisher = eventPublisher;
@Autowired this.performanceAspect = performanceAspect;
private RateLimitAspect rateLimitAspect; this.rateLimitAspect = rateLimitAspect;
}
/** /**
* 学习首页 * 学习首页

View File

@@ -1,64 +1,54 @@
package com.example.demo.controller; package com.example.demo.controller;
import com.example.demo.common.ApiResponse;
import com.example.demo.dto.UserRequest;
import com.example.demo.model.User; import com.example.demo.model.User;
import com.example.demo.service.UserService; import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
/**
* 用户控制器 - RESTful API 示例
*
* 学习点:
* - @RestController: 组合了 @Controller 和 @ResponseBody
* - @RequestMapping: 路由映射
* - @PathVariable: 路径变量
* - @RequestParam: 查询参数
* - @RequestBody: 请求体
*/
@RestController @RestController
@RequestMapping("/api/users") @RequestMapping("/api/users")
public class UserController { public class UserController {
@Autowired private final UserService userService;
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
// GET /api/users - 获取所有用户
@GetMapping @GetMapping
public List<User> getAllUsers() { public ApiResponse<List<User>> getAllUsers() {
return userService.findAll(); return ApiResponse.ok(userService.findAll());
} }
// GET /api/users/{id} - 获取单个用户
@GetMapping("/{id}") @GetMapping("/{id}")
public User getUserById(@PathVariable Long id) { public ApiResponse<User> getUserById(@PathVariable Long id) {
return userService.findById(id); return ApiResponse.ok(userService.findById(id));
} }
// POST /api/users - 创建用户
@PostMapping @PostMapping
public User createUser(@RequestBody User user) { public ApiResponse<User> createUser(@Valid @RequestBody UserRequest req) {
return userService.save(user); User user = new User(null, req.name(), req.email(), req.age());
return ApiResponse.ok("创建成功", userService.create(user));
} }
// PUT /api/users/{id} - 更新用户
@PutMapping("/{id}") @PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) { public ApiResponse<User> updateUser(@PathVariable Long id, @Valid @RequestBody UserRequest req) {
user.setId(id); User user = new User(id, req.name(), req.email(), req.age());
return userService.save(user); return ApiResponse.ok("更新成功", userService.update(id, user));
} }
// DELETE /api/users/{id} - 删除用户
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) { public ApiResponse<Void> deleteUser(@PathVariable Long id) {
userService.delete(id); userService.delete(id);
return "用户 " + id + " 已删除"; return ApiResponse.ok("删除成功", null);
} }
// GET /api/users/search?name=xxx - 搜索用户
@GetMapping("/search") @GetMapping("/search")
public List<User> searchUsers(@RequestParam String name) { public ApiResponse<List<User>> searchUsers(@RequestParam String name) {
return userService.findByName(name); return ApiResponse.ok(userService.findByName(name));
} }
} }

View File

@@ -0,0 +1,19 @@
package com.example.demo.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
public record UserRequest(
@NotBlank(message = "姓名不能为空")
String name,
@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确")
String email,
@Min(value = 1, message = "年龄最小为 1")
@Max(value = 120, message = "年龄最大为 120")
Integer age
) {}

View File

@@ -0,0 +1,38 @@
package com.example.demo.exception;
import com.example.demo.common.ApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiResponse<Void>> handleNotFound(ResourceNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.fail(404, e.getMessage()));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiResponse<Map<String, String>>> handleValidation(MethodArgumentNotValidException e) {
Map<String, String> errors = new HashMap<>();
for (FieldError error : e.getBindingResult().getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
return ResponseEntity.badRequest()
.body(new ApiResponse<>(400, "参数校验失败", errors, java.time.Instant.now()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleAny(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.fail(500, "服务器内部错误: " + e.getMessage()));
}
}

View File

@@ -0,0 +1,7 @@
package com.example.demo.exception;
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}

View File

@@ -1,5 +1,6 @@
package com.example.demo.service; package com.example.demo.service;
import com.example.demo.exception.ResourceNotFoundException;
import com.example.demo.model.User; import com.example.demo.model.User;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -8,23 +9,13 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/**
* 用户服务 - 业务逻辑层
*
* 学习点:
* - @Service: 标记为服务层组件,自动注册为 Bean
* - 依赖注入Controller 通过 @Autowired 注入此服务
* - 分层架构Controller -> Service -> Repository
*/
@Service @Service
public class UserService { public class UserService {
// 内存存储(演示用,实际项目用数据库)
private final List<User> users = new ArrayList<>(); private final List<User> users = new ArrayList<>();
private final AtomicLong idGenerator = new AtomicLong(1); private final AtomicLong idGenerator = new AtomicLong(1);
public UserService() { public UserService() {
// 初始化一些测试数据
users.add(new User(idGenerator.getAndIncrement(), "张三", "zhangsan@example.com", 25)); users.add(new User(idGenerator.getAndIncrement(), "张三", "zhangsan@example.com", 25));
users.add(new User(idGenerator.getAndIncrement(), "李四", "lisi@example.com", 30)); users.add(new User(idGenerator.getAndIncrement(), "李四", "lisi@example.com", 30));
users.add(new User(idGenerator.getAndIncrement(), "王五", "wangwu@example.com", 28)); users.add(new User(idGenerator.getAndIncrement(), "王五", "wangwu@example.com", 28));
@@ -38,7 +29,7 @@ public class UserService {
return users.stream() return users.stream()
.filter(u -> u.getId().equals(id)) .filter(u -> u.getId().equals(id))
.findFirst() .findFirst()
.orElse(null); .orElseThrow(() -> new ResourceNotFoundException("用户不存在: id=" + id));
} }
public List<User> findByName(String name) { public List<User> findByName(String name) {
@@ -47,23 +38,28 @@ public class UserService {
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public User save(User user) { public User create(User user) {
if (user.getId() == null) {
user.setId(idGenerator.getAndIncrement()); user.setId(idGenerator.getAndIncrement());
users.add(user); users.add(user);
} else {
// 更新
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getId().equals(user.getId())) {
users.set(i, user);
break;
}
}
}
return user; return user;
} }
public User update(Long id, User user) {
findById(id);
user.setId(id);
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getId().equals(id)) {
users.set(i, user);
return user;
}
}
throw new ResourceNotFoundException("用户不存在: id=" + id);
}
public void delete(Long id) { public void delete(Long id) {
users.removeIf(u -> u.getId().equals(id)); boolean removed = users.removeIf(u -> u.getId().equals(id));
if (!removed) {
throw new ResourceNotFoundException("用户不存在: id=" + id);
}
} }
} }

View File

@@ -143,7 +143,8 @@ public class UserController {
// 加载用户列表 // 加载用户列表
async function loadUsers() { async function loadUsers() {
const res = await fetch('/api/users'); const res = await fetch('/api/users');
const users = await res.json(); const payload = await res.json();
const users = payload.data || [];
const tbody = document.querySelector('#userTable tbody'); const tbody = document.querySelector('#userTable tbody');
tbody.innerHTML = users.map(u => ` tbody.innerHTML = users.map(u => `
<tr> <tr>
@@ -196,7 +197,7 @@ public class UserController {
await fetch(`/api/users/${id}`, { await fetch(`/api/users/${id}`, {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...user, id: parseInt(id) }) body: JSON.stringify(user)
}); });
} else { } else {
await fetch('/api/users', { await fetch('/api/users', {

View File

@@ -0,0 +1,62 @@
package com.example.demo.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.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.*;
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void shouldListUsersWithApiResponseWrapper() throws Exception {
mockMvc.perform(get("/api/users"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data").isArray());
}
@Test
void shouldCreateUser() throws Exception {
String json = """
{
\"name\": \"测试用户\",
\"email\": \"test@example.com\",
\"age\": 22
}
""";
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.name").value("测试用户"));
}
@Test
void shouldRejectInvalidUser() throws Exception {
String json = """
{
\"name\": \"\",
\"email\": \"bad-mail\",
\"age\": 222
}
""";
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400));
}
}