Skip to content

02 — AOP 与动态代理

定位: Spring AOP 的原理与实现——从代理机制到声明式事务 面试高频度: ⭐⭐⭐⭐⭐

一、板块在体系中的位置

+----------------------------------------------------+
|               AOP 在 Spring 中的位置                  |
|                                                     |
|  01. IoC 容器 (提供基础设施)                          |
|    |                                                 |
|  02. AOP (本板块) 基于 IoC 的代理机制                 |
|    |              |                                  |
|  03. 事务管理     09. 进阶源码                         |
|  (@Transactional) (@Configuration增强)                |
|    |              |                                  |
|  07. Security    05. Spring Boot                      |
|  (方法安全)      (@Enable*注解)                      |
+----------------------------------------------------+

二、知识全景图

+----------------------------------------------------+
|            AOP 核心知识体系                           |
|                                                     |
|  +----------------------------------------------+  |
|  |  1. JDK 动态代理 vs CGLIB                     |  |
|  |  JDK: 接口-based, 创建快但调用慢               |  |
|  |  CGLIB: 继承-based, 创建慢但调用快             |  |
|  +----------------------------------------------+  |
|                      |                              |
|  +----------------------------------------------+  |
|  |  2. AOP 核心概念                               |  |
|  |  JoinPoint -> Pointcut -> Advice -> Aspect     |  |
|  +----------------------------------------------+  |
|                      |                              |
|  +----------------------------------------------+  |
|  |  3. Advice 类型与执行顺序                      |  |
|  |  @Before -> @Around -> @After -> @AfterReturn  |  |
|  +----------------------------------------------+  |
|                      |                              |
|  +----------------------------------------------+  |
|  |  4. @Transactional 底层原理                    |  |
|  |  代理 -> TransactionInterceptor -> 事务管理器   |  |
|  +----------------------------------------------+  |
+----------------------------------------------------+

三、子专题导航

#主题面试频率核心内容
**02.1-JDK动态代理与CGLIB**⭐⭐⭐⭐⭐两种代理原理对比、Spring 选择策略
**02.2-AOP核心概念与Advice**⭐⭐⭐⭐7个核心术语、5种 Advice、Pointcut 表达式
**02.3-@Transactional原理**⭐⭐⭐⭐⭐事务拦截器、同方法调用失效、三种解决方案

四、核心考点速记

考点 1:同方法注解失效

@Service
public class UserService {
    @Transactional public void methodA() {
        methodB();  // B 的 @Transactional 不生效!
    }
    @Transactional public void methodB() {}
}

原因:this.methodB() 调用的是原始对象,不是代理对象。

考点 2:Spring Boot 默认代理方式

Spring Boot 2.0+ 默认 proxyTargetClass=true,优先使用 CGLIB。

考点 3:@Transactional 回滚规则

默认只回滚 RuntimeException 和 Error,checked exception 不回滚。

📚 相关板块

  • **IoC 容器** — AOP 代理在 Bean 生命周期后置处理中生成
  • **事务管理** — @Transactional 基于 AOP 实现

📚 相关链接

  • **Spring文库设计文档** — 文库设计总纲

Knowledge4J — Java 知识库