AOP深度解析:从代码重复到面向切面编程

引子:一个方法的六段重复代码 假设你要实现一个转账方法,按照传统方式,代码可能是这样的: public void transfer(String from, String to, BigDecimal amount) { // ========== 重复代码1:日志记录 ========== log.info("开始转账:{} -> {},金额:{}", from, to, amount); long startTime = System.currentTimeMillis(); try { // ========== 重复代码2:权限校验 ========== User currentUser = SecurityContext.getCurrentUser(); if (!currentUser.hasPermission("TRANSFER")) { throw new PermissionDeniedException("无转账权限"); } // ========== 重复代码3:参数校验 ========== if (amount.compareTo(BigDecimal.ZERO) <= 0) { throw new IllegalArgumentException("金额必须大于0"); } // ========== 重复代码4:事务管理 ========== Connection conn = dataSource.getConnection(); try { conn.setAutoCommit(false); // ========== 核心业务逻辑(只占20%) ========== Account fromAccount = accountDao.getByName(from); Account toAccount = accountDao.getByName(to); fromAccount.setBalance(fromAccount.getBalance().subtract(amount)); toAccount.setBalance(toAccount.getBalance().add(amount)); accountDao.update(fromAccount); accountDao.update(toAccount); // ============================================= conn.commit(); } catch (Exception e) { conn.rollback(); throw e; } finally { conn.close(); } } catch (Exception e) { // ========== 重复代码5:异常处理 ========== log.error("转账失败", e); throw new BusinessException("转账失败:" + e.getMessage()); } finally { // ========== 重复代码6:性能监控 ========== long endTime = System.currentTimeMillis(); log.info("转账完成,耗时:{}ms", endTime - startTime); } } 问题: ...

2025-11-03 · maneng

如约数科科技工作室

浙ICP备2025203501号

👀 本站总访问量 ...| 👤 访客数 ...| 📅 今日访问 ...