Spring 的事务管理把 JDBC/ORM 的「开启、提交、回滚、释放连接」封装成声明式能力:一个
@Transactional注解,方法进出即自动完成事务边界。但要真正用好它,得理解它靠 AOP 代理实现——代理不生效,事务就不生效。
1. 声明式事务
@Service
public class OrderService {
private final OrderMapper orderMapper;
private final InventoryClient inventoryClient;
public OrderService(OrderMapper orderMapper, InventoryClient inventoryClient) {
this.orderMapper = orderMapper;
this.inventoryClient = inventoryClient;
}
@Transactional(rollbackFor = Exception.class)
public void createOrder(OrderCmd cmd) {
orderMapper.insert(cmd.toOrder());
inventoryClient.deduct(cmd.getItemId(), cmd.getQty());
}
}
2026/10/11大约 4 分钟