最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Spring框架-深入理解容器单例池
时间:2026-05-29 17:10:01 编辑:袖梨 来源:一聚教程网
Spring框架中Bean的设计与使用直接影响系统架构质量,本文通过电商下单案例演示分层架构的最佳实践。

Repository 层 — 只管数据库操作
// 专注数据持久化
@Repository
public class OrderRepository {
private final JdbcTemplate jdbc;
public OrderRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public void save(Order order) {
jdbc.update(
"INSERT INTO orders(user_id, product_id, amount) VALUES (?,?,?)",
order.getUserId(), order.getProductId(), order.getAmount()
);
}
public List findByUserId(Long userId) {
return jdbc.query(
"SELECT * FROM orders WHERE user_id = ?",
(rs, row) -> new Order(rs.getLong("id"), rs.getLong("user_id")),
userId
);
}
}
Service 层 — 业务逻辑中枢
// 协调多个Repository完成业务目标
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final UserRepository userRepository;
public OrderService(OrderRepository orderRepository,
UserRepository userRepository) {
this.orderRepository = orderRepository;
this.userRepository = userRepository;
}
@Transactional
public Order placeOrder(Long userId, Long productId, BigDecimal amount) {
User user = userRepository.findById(userId);
if (user == null || user.getBalance().compareTo(amount) < 0) {
throw new RuntimeException(user == null ? "用户不存在" : "余额不足");
}
userRepository.deductBalance(userId, amount);
Order order = new Order(userId, productId, amount);
orderRepository.save(order);
return order;
}
}
Controller 层 — 请求处理网关
@RestController
@RequestMapping("/orders")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@PostMapping
public ResponseEntity placeOrder(@RequestBody PlaceOrderRequest req) {
try {
Order order = orderService.placeOrder(
req.getUserId(),
req.getProductId(),
req.getAmount()
);
return ResponseEntity.ok("下单成功,订单ID:" + order.getId());
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
}
核心设计原则
分层隔离:各层仅通过接口通信,Controller不越权处理业务,Service不直接操作数据库。
无状态设计:所有Bean字段均为final,业务数据通过方法参数传递。
依赖单向:严格遵循Controller→Service→Repository的调用方向。
通过电商下单案例的完整实现,展示了Spring Bean分层设计的核心要点与线程安全机制,这种架构模式能有效支撑高并发业务场景。