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

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