第20章 卷六 · 套壳 · 递到手的不是原件:AOP 总纲
卷六 · 套壳
递到⼿的不是原件:AOP 总纲"这个接⼝不是给 Spring ⽤户⽤的,⽽是为了让对不同类型通知的⽀持有⼀个共同的抽象。" —— 不是我说的,是 Advisor 这个接⼝⾃⼰的 javadoc 原话。 [framework]spring-aop/src/main/java/org/springframework/aop/Advisor.java:24-25开场:那个⽅法明明加了注解,为什么什么都没发⽣前五卷,我们⼀直在看同⼀件事:你不⾃⼰找料、不⾃⼰造配件——只在图纸上写清要什么,坊⾥造好、配好、递到你⼿上。
图纸( BeanDefinition )、作坊( BeanFactory )、总装房( ApplicationContext )、⼗⼆道⼯序( refresh() )、榫卯(依赖注⼊)、半成品先递出去(三级缓存)——都讲透了。到这⾥,"料从哪来"这个问题已经没有秘密了。
现在轮到后半句,也是全书真正的分⽔岭:
递到你⼿上的,常常不是原件。
我第⼀次撞上这件事,是在⼀个再普通不过的下午。有⼈拿着⼀段代码来问我:
//示意代码,⾮本仓源码@Service
public class OrderService {@Transactional
public void doPay(long id) { /*扣款、记账、发消息 */ }
public void batch(List<Long> ids) {
for (long id : ids) {
this.doPay(id); // ←就这⼀⾏
}
}
}问题是:外部调 doPay(1L) ,事务⽣效;外部调 batch(...) ,⾥⾯那⼀圈 this.doPay(id) ,事务⼀次都没⽣效。
不报错。不打警告。⽇志⾥⼲⼲净净。数据也确实写进去了——只是没有事务边界,第三笔炸了,前两笔不回滚。
那天我给出的解释是"⾃调⽤不⾛代理"。这个解释是对的,但它是背下来的。真正让⼈⼼⾥踏实的解释,得从⼀个更冒犯的事实开始:
你在 batch ⽅法⾥写的那个 this ,和外部注⼊到别⼈字段⾥的那个 orderService ,根本不是同⼀个对象。
不是"引⽤不同",是类不同。你可以⾃⼰验:
//示意代码,⾮本仓源码
System.out.println(orderService.getClass());//可能打印:class com.x.OrderService$$SpringCGLIB$$0
System.out.println(AopUtils.isAopProxy(orderService)); // true
System.out.println(AopUtils.getTargetClass(orderService)); // class com.x.OrderServiceisAopProxy 的判据摆在 [framework] spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java:82-85 :先看它是不是 SpringProxy ,再看它是 JDK 代理还是类名⾥带 CGLIB 分隔符。⽽ getTargetClass ( :123-133 )对 CGLIB 代理的做法直⽩得可爱——取 getSuperclass() 。因为 CGLIB 代理就是⽬标类的⼀个运⾏期⼦类。


于是那⼀⾏ this.doPay(id) , this 指向的是⼦类⾥那个被继承下来的原始⽅法体,它是从代理内部往下⾛的,压根没有再经过⼀次代理⼊⼝。
壳只能拦住从外⾯进来的调⽤。你⾃⼰在壳⾥⾯喊⾃⼰⼈,喊声传不到壳上。
这⼀卷讲的就是这个壳:它是什么、谁给套的、套在哪、以及——最重要的——它罩不住什么。
本章是总纲。我不打算⼀上来就讲 JDK 和 CGLIB 怎么⽣成字节码(那是下⼀章的事),我要先做⼀件更要紧的事:把三条边界钉死。因为后⾯所有"为什么我的@Transactional / @Cacheable / @Async 不⽣效"的问题,追到底都会落在这三条⾥的某⼀条上。
⼀、先钉三条边界Spring AOP 不是 AspectJ 的简化版,它是另⼀条技术路线。AspectJ 改字节码,Spring AOP ⼀个字节都不改,它只是换掉你⼿上拿到的那个引⽤。
由此推出三条硬边界。我先把结论摆出来,再逐条给证据。
边界 结论织⼊粒度 只有⽅法执⾏⼀种连接点。没有字段读写、没有构造器、没有异常处理器作⽤范围 只对Spring 容器管理的 bean ⽣效(唯⼀例外:你⾃⼰⼿写 ProxyFactory )
织⼊⽅式 基于运⾏时代理,不是字节码织⼊1.1 边界⼀:这世上只有"⽅法执⾏"⼀个连接点官⽅⽂档⾥那句话,措辞⾥有个 always ,是刻意的:
"Join point: A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point alwaysrepresents a method execution." —— [framework] framework-docs/modules/ROOT/pages/core/aop/introduction-defn.adoc:13-15但⽐⽂档更有意思的,是源码⾥那句⼆⼗多年前留下的话。 BeforeAdvice 是个空的标记接⼝,它的 javadoc 只有两⾏:
/**
* Common marker interface for before advice, such as {@link MethodBeforeAdvice}.*
* <p>Spring supports only method before advice. Although this is unlikely to change,- this API is designed to allow field advice in future if desired.
*/
public interface BeforeAdvice extends Advice {
}[framework] spring-aop/src/main/java/org/springframework/aop/BeforeAdvice.java:24-30"设计上允许将来⽀持字段通知,如果需要的话。"
这个接⼝有多⽼? BeforeAdvice.java 和 MethodBeforeAdvice.java 上连⼀个 @since 标签都没有,只有⼀⾏ @author Rod Johnson ——那个年代的类还没养成打@since 的习惯。真正的年轮刻在隔壁:
/**
- Tag interface for Advice. ...
*
- @author Rod Johnson
- @version $Id: Advice.java,v 1.1 2004/03/19 17:02:16 johnsonr Exp $
*/
[framework] spring-aop/src/main/java/org/aopalliance/aop/Advice.java:20-24那是⼀枚 CVS 关键字化⽯——2004 年 3 ⽉ 19 ⽇ 17:02:16, johnsonr 提交了这个⽂件的 1.1 版本。⼆⼗多年过去,版本控制系统从 CVS 换到 SVN 再换到 Git,这⾏ $Id$再也没有被任何⼯具展开过,就这么原样留在 Framework 7.1 的主⼲上。
⽽那个 "in future" 的字段通知,也依然是 future。⽂档已经不装了,直接写成了现在时:
"Field interception is not implemented, although support for field interception could be added without breaking the core Spring AOP APIs. If you need to advisefield access and update join points, consider a language such as AspectJ." —— [framework] framework-docs/.../core/aop/introduction-spring-defn.adoc:8-11如果你觉得这只是⽂档⼝径,我这⾥有⼀件实物证据。
Spring 把 AOP Alliance 的那套接⼝直接 fork 进了⾃⼰的源码树——不是外部依赖,是就地拷⻉。构建脚本⾥那⾏注释写得明明⽩⽩:
compileOnly("com.google.code.findbugs:jsr305") // for the AOP Alliance fork ([framework] spring-aop/spring-aop.gradle:8 )。fork 进来的包⾥躺着⼋个⽂件:
spring-aop/src/main/java/org/aopalliance/intercept/ConstructorInterceptor.java ← 注意这个ConstructorInvocation.java ← 和这个Interceptor.javaInvocation.javaJoinpoint.javaMethodInterceptor.javaMethodInvocation.javapackage-info.java
我在整个 org.springframework 包下 grep 了⼀遍 ConstructorInterceptor :
零命中。
整个 spring-framework 仓库⾥提到 ConstructorInterceptor 的,只剩三处,⽽且全部在 org.aopalliance 这个 fork 包内部⾃⼰引⾃⼰:它⾃⼰的接⼝声明与 javadoc示例( ConstructorInterceptor.java:29, 44 )、 ConstructorInvocation.java:29 的⼀句 @see 、 Interceptor.java:36 javadoc ⾥的⼀段代码样例。跨出这个包,零命中。Spring 从来没有实现过构造器拦截,⼀次都没有。 那两个类在源码树⾥躺了⼆⼗年,是规范留下的空位,是化⽯。
这是"只做⽅法级"最硬的⼀条实物证据——不是⽂档说的,是 grep 说的。
1.2 边界⼆:只对容器管理的 bean ⽣效这条的证据只有⼀⾏,但那⼀⾏定⽣死:
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {[framework] spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java:96-97⾃动代理是⼀个 BeanPostProcessor 。
回想卷三讲的"过⼿的⼈"——每件器成形前后都要过他们的⼿,他们可以掉包。⾃动代理创建器就是掉包掉得最狠的那⼀个:
@Override
public @Nullable Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyBeanReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}[framework] spring-aop/.../framework/autoproxy/AbstractAutoProxyCreator.java:285-293看清楚 return wrapIfNecessary(...) 这⼀⾏。整件事的全部魔法就在这⼉:你⾟⾟苦苦造好、注好、初始化完的那件器,在最后⼀道⼯序上被换成了另⼀个对象。
wrapIfNecessary ( :321-345 )三步:先跳过基础设施类,再问"这个 bean 有没有适⽤的 advisor",有就 createProxy(..., new SingletonTargetSource(bean)) 。原件被包进 TargetSource 塞进壳⾥,壳被返回给容器,容器把壳注册成单例,注给所有需要它的⼈。
推论是残酷的:任何没有经过容器 getBean() 的对象,都不会进这个回调,⾃然不会被套壳。
你 new 出来的对象——没戏。
JPA/Hibernate 通过反射实例化的实体——没戏。
静态⼯具类——没戏。
@Configuration ⾥你⼿动 new 出来再 return 的?那个倒是有戏,因为它的返回值⾛了容器;但你在别的 @Bean ⽅法⾥直接 new 的临时对象,没戏。
顺带说⼀个反向的边界。 isInfrastructureClass 定义了永不代理的四类东⻄:
protected boolean isInfrastructureClass(Class<?> beanClass) {
boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
Pointcut.class.isAssignableFrom(beanClass) ||
Advisor.class.isAssignableFrom(beanClass) ||
AopInfrastructureBean.class.isAssignableFrom(beanClass);...
}[framework] spring-aop/.../framework/autoproxy/AbstractAutoProxyCreator.java:359-368Advice、Pointcut、Advisor、 AopInfrastructureBean ——做壳的⼈不能被套壳,否则就是⽆穷递归。这是本坊的⾏规。
那么"只对容器 bean ⽣效"有没有例外?有,⽽且只有⼀个⼝⼦: ProxyFactory 。⽂档给了它⼀句很直接的定位:
"It is easy to create AOP proxies programmatically with Spring. This lets you use Spring AOP without dependency on Spring IoC." —— [framework] framework-docs/modules/ROOT/pages/core/aop-api/prog.adoc:4-5你可以完全脱离容器,⾃⼰ new ProxyFactory(target) 、⾃⼰ addAdvice 、⾃⼰ getProxy() 。但注意——代理引⽤是你拿到⼿的,你得⾃⼰负责把它传下去。你要是转⼿把 target ⽽不是 proxy 交出去,⼀切照样⽩搭。这个⼝⼦没有推翻边界,只是把"谁负责持有代理引⽤"从容器换成了你。
1.3 边界三:基于代理,不是织⼊"Spring AOP is implemented in pure Java. There is no need for a special compilation process. Spring AOP does not need to control the class loader hierarchy andis thus suitable for use in a servlet container or application server." —— [framework] framework-docs/.../core/aop/introduction-spring-defn.adoc:4-6这句话在 2004 年是⼀句巨⼤的卖点。那年头玩 AOP 意味着你要引⼊ ajc 编译器、改构建流程、或者挂⼀个 -javaagent 。Spring 说:不⽤,纯 Java,运⾏期给你⽣成个代理就完了。
代价就是这三条边界。
最容易引起误会的是 Spring 与 AspectJ 的关系。很多⼈看到 @Aspect 、 @Pointcut 、 execution(...) 就以为"Spring ⽤了 AspectJ"。Spring 只借了 AspectJ 的切点语⾔,没借它的织⼊器。 这话不是我下的定论,是 org.springframework.aop.aspectj 这个包的 package-info ⾃⼰写的:
"Note that use of this package does not require the use of the ajc compiler or AspectJ load-time weaver. It is intended to enable the use of a valuable subsetof AspectJ functionality, with consistent semantics, with the proxy-based Spring AOP framework." —— [framework] spring-aop/src/main/java/org/springframework/aop/aspectj/package-info.java:7-9
构建依赖印证了这⼀点: optional("org.aspectj:aspectjweaver") ([framework] spring-aop/spring-aop.gradle:10 )。aspectjweaver 是 optional 依赖,spring-aop 把它当成⼀个"切点表达式解析器"⽤,仅此⽽已。
⽂档甚⾄专⻔为⼀个 XML 标签名字写了⼀段警告,因为那个名字骗了太多⼈:
"Do not be misled by the name of the <aop:aspectj-autoproxy/> element. Using it results in the creation of Spring AOP proxies. The @AspectJ style of aspectdeclaration is being used here, but the AspectJ runtime is not involved." —— [framework] framework-docs/.../core/aop/using-aspectj.adoc:353-355
⚠ 三条边界的共同罪状:它们全部是静默的。
这是我对 Spring AOP 最实在的⼀条批评。你在 final 类上加 @Transactional ,不报错;你在同类⾥ this. 调⼀个带注解的⽅法,不报错;你给⼀个 new 出来的对象加@Cacheable ,不报错。它们只是不⽣效。 框架有⾜够的信息在启动期发现前两种情况( final 类是编译期就确定的,同类⾃调⽤也是可以静态分析的),却选择了沉默。
这不是疏忽,是权衡:Spring 不知道你那个 final 类上的注解是给⾃⼰⽤的还是给 AspectJ LTW ⽤的,贸然报错会误伤。但对使⽤者来说,"静默失效"永远是最贵的失败模式——它把发现成本从编译期推到了⽣产环境的对账单上。
⼆、四个词:Advice、Pointcut、Advisor、Aspect边界钉完了,说词。
Spring 在这件事上做过⼀个我很欣赏的决定:不⾃造术语。⽂档开篇就交代了理由:
"These terms are not Spring-specific. Unfortunately, AOP terminology is not particularly intuitive. However, it would be even more confusing if Spring used itsown terminology." —— [framework] framework-docs/.../core/aop/introduction-defn.adoc:4-6翻成坊⾥话,这四个词是这么对上的:
AOP 术语 坊⾥话 ⼀句话Advice 壳上刻的⼯序 ⼲什么Pointcut ⼯序刻在哪些位置 在哪⼉⼲Advisor ⼯序 + 位置,⼀整套 框架内部唯⼀认的单位Aspect ⼀张⼯艺卡(会被拆掉) 你写的那个 @Aspect 类下⾯逐个拆。
2.1 Advice 是个空接⼝——这是设计,不是偷懒/**
- Tag interface for Advice. Implementations can be any type
- of advice, such as Interceptors.
*/
public interface Advice {
}[framework] spring-aop/src/main/java/org/aopalliance/aop/Advice.java:26-28⼀个⽅法都没有。第⼀次看到的⼈多半会想:"这也太敷衍了。"
不是敷衍。空接⼝在这⼉是为了容纳多种形态:
通知形态 接⼝ 坐标 ⽅法签名
环绕(原⽣) MethodInterceptor [framework] .../org/aopalliance/intercept/MethodInterceptor.java:45 Object invoke(MethodInvocation)
前置 MethodBeforeAdvice [framework] .../aop/MethodBeforeAdvice.java:31 void before(Method, Object[], Object)
返回后 AfterReturningAdvice [framework] .../aop/AfterReturningAdvice.java:31 void afterReturning(Object, Method, Object[], Object)抛异常后 ThrowsAdvice [framework] .../aop/ThrowsAdvice.java:51 没有⽅法最后⼀⾏不是笔误。 ThrowsAdvice 也是个空接⼝,它靠⽅法签名约定⼯作:
"There are not any methods on this interface, as methods are invoked by reflection. Implementing classes must implement methods of the form: void
afterThrowing([Method, args, target], ThrowableSubclass); " —— [framework] spring-aop/.../aop/ThrowsAdvice.java:22-25这⾥必须批评⼀句。 这种"约定式接⼝"在 2003 年是没办法的办法——那时候没有泛型可⽤(Java 5 还没发布),没有注解,要⽀持"按异常类型分派"只能靠反射扫⽅法。但它带来的后果⼀直留到今天:你把 afterThrowing 拼成了 afterThrown ,编译器不会说话,IDE 不会说话,启动不会说话,只是那段异常处理逻辑永远不会跑。这是"边界静默"之
外,Spring AOP 的第⼆处静默。
好消息是这条路今天基本没⼈⾛了—— @AfterThrowing 注解在编译期⾄少能拼对注解名。坏消息是⽼代码库⾥这种东⻄还活着。
2.2 Pointcut = ClassFilter × MethodMatcherPointcut 是整个匹配体系的根,有效内容只有三⾏:
public interface Pointcut {
ClassFilter getClassFilter();
MethodMatcher getMethodMatcher();
Pointcut TRUE = TruePointcut.INSTANCE;
}[framework] spring-aop/src/main/java/org/springframework/aop/Pointcut.java:33-51javadoc 第⼀句就点明了组合语义:"A pointcut is composed of a ClassFilter and a MethodMatcher ."( :22-24 )
两级过滤:先粗筛类,再细筛⽅法。 这个顺序不是随便定的——类级过滤⼀次就能否掉⼀整个 bean 的所有⽅法,代价远⼩于逐⽅法匹配。
⽽ MethodMatcher ⾥藏着全 Spring AOP ⾥最容易被忽略、代价却最⾼的⼀个设计点:它有两个 matches 重载。
public interface MethodMatcher {
boolean matches(Method method, Class<?> targetClass); // 2参:静态
boolean isRuntime(); //分⽔岭
boolean matches(Method method, Class<?> targetClass, @Nullable Object... args); // 3参:动态
}[framework] spring-aop/src/main/java/org/springframework/aop/MethodMatcher.java:61-105isRuntime() 就是那个开关。javadoc 讲得⽐我清楚:
"If an implementation returns false from its isRuntime() method, evaluation can be performed statically, and the result will be the same for all invocations of
this method, whatever their arguments. This means that if the isRuntime() method returns false , the 3-arg matches(Method, Class, Object[]) methodwill never be invoked." —— MethodMatcher.java:31-35反过来呢:
"the 3-arg matches(...) method will be invoked immediately before each potential execution of the related advice ... All previous advice, such as earlierinterceptors in an interceptor chain, will have run, so any state changes they have produced in parameters or ThreadLocal state will be available at the time ofevaluation." —— MethodMatcher.java:37-44翻译成⼈话:你写 execution(* com.x.*.*(..)) ,静态匹配,装配期算⼀次,之后永久缓存;你写 args(java.io.Serializable) 这类需要看实参的表达式,isRuntime() 变 true,于是每⼀次⽅法调⽤都要重跑⼀遍匹配。
很多⼈把"AOP 慢"归咎于代理本身。代理确实有开销,但那点开销在现代 JIT ⾯前基本可以忽略。真正的⼤头往往在这⾥——你不⼩⼼写了个动态切点,然后它在每秒⼏万次的热路径上被反复求值。
2.3 Advisor = Pointcut + Advice ——全书最值钱的⼀句话这句话不是助记⼝诀,它在源码⾥有字⾯对应:
public interface Advisor {
Advice getAdvice(); // :55⼲什么
}
public interface PointcutAdvisor extends Advisor {
Pointcut getPointcut(); // :31在哪⼉⼲
}[framework] spring-aop/.../aop/Advisor.java:36-55 、 spring-aop/.../aop/PointcutAdvisor.java:26-31⽂档给的定义更精确⼀点,注意⾥⾯的 "only a single":
"In Spring, an Advisor is an aspect that contains only a single advice object associated with a pointcut expression." —— [framework] framework-docs/.../core/aop-api/advisor.adoc:5-6⼀个 Advisor 只带⼀条 advice。 这就是为什么⼀个 @Aspect 类会被拆成好⼏个 Advisor——它身上通常有好⼏个通知⽅法。
Advisor 家族只有两⽀, PointcutAdvisor 的 javadoc ⾃⼰划的:
"Superinterface for all Advisors that are driven by a pointcut. This covers nearly all advisors except introduction advisors, for which method-level matchingdoesn't apply." —— PointcutAdvisor.java:20-22PointcutAdvisor :有⽅法级匹配。⽇常 99% 的场景都在这⽀—— @Before 、 @Around 、事务、缓存、 @Async 、重试、安全,全在这⼉。
IntroductionAdvisor :只有类级匹配。它⼲的是"给⼀个类塞⼀个它本来没实现的接⼝"(AspectJ 管这叫 inter-type declaration),⽅法级匹配对它没有意义。
⽽开篇引⽤的那句⾃⽩,现在可以还原到语境⾥了:
"This interface is not for use by Spring users, but to allow for commonality in support for different types of advice." —— Advisor.java:24-25Advisor 是框架内部的统⼀货币。 你写 @Aspect 、写 XML、写 MethodInterceptor 、写 MethodBeforeAdvice ——什么形态都⾏,框架在背后统统换算成 Advisor ,存进同⼀个 List<Advisor> 。多⼊⼝,单内表。
这条设计约束贯穿整个 AOP 模块,后⾯每⼀层都在吃它的红利。
2.4 那 Aspect 呢?——它在运⾏期根本不存在你写了⼀个 @Aspect 类,它被扫进容器,然后呢?
然后它就被拆了。
Aspect 在 Spring AOP ⾥没有任何对应的运⾏时 Java 类型——没有 org.springframework.aop.Aspect 这个接⼝,找不到的。⼀个 @Aspect 类在装配期会被ReflectiveAspectJAdvisorFactory 拆成⼀组 Advisor:
@Override
public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
validate(aspectClass);...
List<Advisor> advisors = new ArrayList<>();
for (Method method : getAdvisorMethods(aspectClass)) { //每个通知⽅法
if (method.equals(ClassUtils.getMostSpecificMethod(method, aspectClass))) {
Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, 0, aspectName);
if (advisor != null) {
advisors.add(advisor); // →⼀个 Advisor
}
}
}...
for (Field field : aspectClass.getDeclaredFields()) { // @DeclareParents字段
Advisor advisor = getDeclareParentsAdvisor(field);
if (advisor != null) {
advisors.add(advisor);
}
}
return advisors;
}[framework] spring-aop/.../aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java:123-166⼀个通知⽅法 → ⼀个 Advisor。 切点来⾃注解⾥的表达式,被解析成 AspectJExpressionPointcut ;通知则由⼀个 switch 按注解类型映射( :268-299 附近):
你写的注解 变成的 Advice 实现类@Around AspectJAroundAdvice@Before AspectJMethodBeforeAdvice@After AspectJAfterAdvice@AfterReturning AspectJAfterReturningAdvice@AfterThrowing AspectJAfterThrowingAdvice@Pointcut 不产⽣ advice(纯签名,返回 null)
所以那张"⼯艺卡"( @Aspect 类)在开⼯之前就被剪成了⼀条条⼯序单,卡⽚本身进了废纸篓——运⾏期只有 Advisor,没有 Aspect。
⚠ 顺⼿挖出⼀个排序陷阱。 这个陷阱不需要我推测,源码⾥有⼀段作者亲⼿写的注释解释它:
static {// Note: although @After is ordered before @AfterReturning and @AfterThrowing,// an @After advice method will actually be invoked after @AfterReturning and
// @AfterThrowing methods due to the fact that AspectJAfterAdvice.invoke(MethodInvocation)
// invokes proceed() in a `try` block and only invokes the @After advice method// in a corresponding finally block.
Comparator<Method> adviceKindComparator = new ConvertingComparator<Method, @Nullable Annotation>(
new InstanceComparator<>(
Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class),
...);...
}[framework] spring-aop/.../aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java:80-94 (那段注释在 :81-85 )
排序器⾥ After 排在 AfterReturning 、 AfterThrowing 前⾯,但实际执⾏时 @After 在后⾯跑。原因是 AspectJAfterAdvice 把 proceed() 放在 try ⾥、把@After ⽅法放在 finally ⾥——链上靠前 = 栈上靠外 = finally 最后跑。
排序表和执⾏顺序看起来⽭盾,其实是同⼀件事的两⾯。这种地⽅,注释⽐代码值钱。
🦴 同⼀段代码往下⼏⾏,还埋着⼀块考据级化⽯:
"Prior to Spring Framework 5.2.7, advisors.size() was supplied as the declarationOrderInAspect to getAdvisor(...) to represent the 'current position'in the declared methods list. However, since Java 7 the 'current position' is not valid since the JDK no longer returns declared methods in the order in which they
are declared in the source code. Thus, we now hard code the declarationOrderInAspect to 0 for all advice methods discovered via reflection in order to supportreliable advice ordering across JVM launches." —— ReflectiveAspectJAdvisorFactory.java:136-143翻译:曾经 Spring ⽤"这个通知⽅法是类⾥第⼏个"来定优先级,直到有⼈发现 JDK 7 之后 getDeclaredMethods() 不保证源码顺序——同⼀份 class ⽂件,换个 JVM 启动,通知顺序可能就变了。修法是把这个序号硬编码成 0,彻底不⽤它,改由 @Order 之类的显式⼿段决定。
⼀个"看起来能⽤"的隐含假设,撑了⼗⼏年,最后被⼀句"JDK 不保证"掀翻。这就是为什么不能依赖未⽂档化的顺序。
三、 ProxyFactory 与 AdvisedSupport :壳的图纸和造壳的⼿现在我们有⼀堆 Advisor 了。谁来把它们装成⼀个壳?
答案在⼀条四层继承链上。这条链看起来很"企业级 Java",但每⼀层都有明确的职责:
ProxyFactory ⻔⾯:⼏个构造器 + getProxy()
└ ProxyCreatorSupport 选⼯⼚ + 激活标志 + 监听器
└ AdvisedSupport ★ 真正的数据结构:advisors / interfaces / targetSource / 三层缓存
└ ProxyConfig 5 个开关
└ Serializable逐层坐标(都在 [framework] spring-aop/src/main/java/org/springframework/aop/framework/ 下): ProxyFactory.java:36 → ProxyCreatorSupport.java:33→ AdvisedSupport.java:68 → ProxyConfig.java:33 。
⽂档对这条链有⼀句总结: AdvisedSupport is the superclass of both ProxyFactory and ProxyFactoryBean ( prog.adoc:45-46 )。
3.1 ProxyFactory 是个瘦得离谱的⻔⾯ProxyFactory 全类不到 170 ⾏,它的⾃我定位很直⽩:
"Factory for AOP proxies for programmatic use, rather than via declarative setup in a bean factory." —— [framework] spring-aop/.../framework/ProxyFactory.java:26-28它⾃⼰⼏乎不⼲活,最核⼼的⽅法就⼀⾏:
public Object getProxy() {
return createAopProxy().getProxy();
}ProxyFactory.java:96-98
就这⼀⾏。 createAopProxy() 是⽗类 ProxyCreatorSupport 的, getProxy() 是 AopProxy 的。 ProxyFactory 只是把两者串起来。✨ 有个容易被忽略的细节藏在 javadoc ⾥:
"Can be called repeatedly. Effect will vary if we've added or removed interfaces. Can add and remove interceptors." —— ProxyFactory.java:90-91同⼀个 ProxyFactory 可以反复产代理,中途改了配置,产出来的壳就不⼀样。它不是⼀次性的。
另有⼀个 Framework 6.0 加的⽅法值得记⼀笔:
/**
- ...
- @since 6.0
*/
public Class<?> getProxyClass(@Nullable ClassLoader classLoader) {
return createAopProxy().getProxyClass(classLoader);
}ProxyFactory.java:120-122只要代理类,不要实例。 这是给 AOT / GraalVM native image ⽤的——构建期需要提前知道"会⽣成哪些代理类"好把它们注册进反射配置,但那时候还没法真的实例化 bean。
这是 Spring ⾛向 native 的⼀枚⼩螺丝。
⾄于 ProxyCreatorSupport ,它只加了两件事:
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}ProxyCreatorSupport.java:101-106选⼯⼚(默认 DefaultAopProxyFactory.INSTANCE , :47 ),以及"第⼀次产代理时激活并通知监听器"。注意 createAopProxy() 是 synchronized ,⽽adviceChanged() ⾥也有 synchronized (this) ( :126 )——配置变更与代理创建之间的可⻅性,靠的是这把对象锁。
还有⼀个细节: return getAopProxyFactory().createAopProxy(this) ⾥那个 this 。它把⾃⼰整个(作为 AdvisedSupport )交了出去。 壳⽣成器拿到的不是⼏个参数,是⼀整份配置快照。
3.2 AdvisedSupport 才是⼼脏747 ⾏,全篇的重量都在这⼉。它的 javadoc 第⼀件事是澄清⾃⼰不是什么:
"Base class for AOP proxy configuration managers. These are not themselves AOP proxies, but subclasses of this class are normally factories from which AOPproxy instances are obtained directly. ... This class is used to hold snapshots of proxies." —— [framework] spring-aop/.../framework/AdvisedSupport.java:50-61⽤坊⾥话说: AdvisedSupport 不是壳,是"这个壳该怎么做"的图纸。
这和全书第⼀章点破的那件事是同构的—— BeanDefinition 不是 Bean, AdvisedSupport 不是代理。图纸和成品,始终要分清。
核⼼字段( :80-129 ),每⼀个的注释都值得读:
字段 ⾏ ⻔道TargetSource targetSource :85包级可⻅。上⾯那⾏注释是 /** Package-protected to allow direct access for efficiency. */ ——为了让JdkDynamicAopProxy / CglibAopProxy 直接读字段,省⼀次⽅法调⽤
boolean preFiltered = false :88 默认 false。true 表示 advisor 已按⽬标类预筛过,运⾏期可跳过 ClassFilterAdvisorChainFactoryadvisorChainFactory:92 默认 DefaultAdvisorChainFactory.INSTANCE
List<Class<?>> interfaces :99 注释写明⽤ List 不⽤ Set:"to keep the order of registration, to create JDK proxy with specified order of interfaces"——顺序敏感
List<Advisor> advisors :106 注释:"If an Advice is added, it will be wrapped in an Advisor"——⼀切最终都是 Advisor
List<Advisor> advisorKey :115 @since 6.0.10 ,代理类缓存 key,⻅ 🦴
Map<MethodCacheKey, List<Object>>methodCache:118 transient ,⽅法级链缓存
List<Object> cachedInterceptors :121 transient volatile ,⽆⽅法级切点时的共享链Object proxyMetadataCache :129 @since 6.1.3 ,给 JdkDynamicAopProxy 存元数据还有⼀个常量值得单说:
/**
- Canonical TargetSource when there's no target, and behavior is
- supplied by the advisors.
*/
public static final TargetSource EMPTY_TARGET_SOURCE = EmptyTargetSource.INSTANCE;AdvisedSupport.java:76-80可以完全没有⽬标对象。 ⾏为全部由 advice 提供。远程调⽤代理、Mock 对象、纯接⼝桩,都是这么玩的——壳⾥⾯是空的,所有调⽤被拦截器接住、⾃⼰造出返回值。壳可以脱离原件独⽴存在。
3.3 addAdvice() :⼀颗糖⾐炮弹前⾯说过"⼀切最终都变成 Advisor"。这个"变"的动作,就在这⾥:
@Override
public void addAdvice(int pos, Advice advice) throws AopConfigException {
Assert.notNull(advice, "Advice must not be null");
if (advice instanceof IntroductionInfo introductionInfo) {// We don't need an IntroductionAdvisor for this kind of introduction:
// It's fully self-describing.
addAdvisor(pos, new DefaultIntroductionAdvisor(advice, introductionInfo));
}
else if (advice instanceof DynamicIntroductionAdvice) {// We need an IntroductionAdvisor for this kind of introduction.
throw new AopConfigException("DynamicIntroductionAdvice may only be added as part of IntroductionAdvisor");
}
else {
addAdvisor(pos, new DefaultPointcutAdvisor(advice)); //★
}
}[framework] spring-aop/.../framework/AdvisedSupport.java:435-449看最后那个 else :⼀条光秃秃的 advice,被裹进 DefaultPointcutAdvisor 。⽽ DefaultPointcutAdvisor 的单参构造给的切点是—— Pointcut.TRUE 。
匹配⼀切。
⚠ 这就是暗礁。 Advised 接⼝的 javadoc 亲⾃把话挑明了,⽽且在两个重载上各说了⼀遍,可⻅踩的⼈有多少:
"Note that the given advice will apply to all invocations on the proxy, even to the toString() method! Use appropriate advice implementations or specify
appropriate pointcuts to apply to a narrower set of methods." —— [framework] spring-aop/.../framework/Advised.java:186-188 ( addAdvice(int, Advice)处⼜重复⼀遍, :201-203 )
factory.addAdvice(myInterceptor) 看着多⽅便啊——⼀⾏搞定。然后你的⽇志拦截器开始给 toString() 、 hashCode() 、 equals() 打⽇志,某个调试时的System.out.println(obj) 触发了⼀整条事务链。
便利 API 背后是 Pointcut.TRUE 。 这不是 bug,是你没读那三⾏ javadoc 的代价。
3.4 ProxyConfig 的五个开关,以及 Framework 7 悄悄做的⼀件⼤事
public class ProxyConfig implements Serializable {
private @Nullable Boolean proxyTargetClass;
private @Nullable Boolean optimize;
private @Nullable Boolean opaque;
private @Nullable Boolean exposeProxy;
private @Nullable Boolean frozen;[framework] spring-aop/.../framework/ProxyConfig.java:33-47注意类型:是包装类 Boolean ,不是基本类型 boolean 。 五个字段全是 @Nullable 。这是⼀个三态设计——先记住这⼀点,⼀会⼉⻅分晓。
默认值(全部回源核实,别信⽹上的⼆⼿说法):
开关 语义默认值判据proxyTargetClass 直接代理⽬标类⽽⾮接⼝ false
isProxyTargetClass() 是 (this.proxyTargetClass != null && this.proxyTargetClass) , :69-71 ;javadoc 明写 "Default is\"false\"", :52optimize 激进优化 false:89-91 。javadoc:"this flag effectively enforces CGLIB proxies(类似 setProxyTargetClass )but without any class validation
checks (for final methods etc)", :77-80opaque阻⽌代理被强转成Advisedfalse :107-109 。javadoc:"Default is \"false\", meaning that any AOP proxy can be cast to Advised ", :96-97exposeProxy把代理放进ThreadLocalfalse :128-130 。 Advised 的 javadoc 补了⼀句:"Default is false , for optimal performance", Advised.java:81frozen冻结配置,不许改advicefalse :145-147两条值得展开:
optimize 是个陷阱名。 它听起来像"打开就更快",实际语义是"跳过 final ⽅法等类校验,强上 CGLIB"。跳过校验意味着你在⼀个有 final ⽅法的类上开了它,那些 final⽅法不会报错,只是默默不被增强。⼜⼀处静默。别碰它。
opaque=false 是能⼒,也是⻛险。 默认情况下:
//示意代码,⾮本仓源码
((Advised) orderService).removeAdvisor(0); //把事务拆了任何拿到这个 bean 的代码,都能把它的 advisor 摘掉。 这不是漏洞,是设计—— Advised 是代理的⾃省接⼝,⽂档写着 "Any AOP proxy obtained from Spring can be
cast to this interface to allow manipulation of its AOP advice"( Advised.java:30-31 )。想堵这个⼝⼦,要么 setOpaque(true) ,要么 setFrozen(true) (frozen 时removeAdvisor 会抛 AopConfigException , AdvisedSupport.java:328-331 )。
现在回到"为什么是 Boolean 不是 boolean "。答案是 Framework 7 新增的这个⽅法:
/**
- Copy default settings from the other config object,
- for settings that have not been locally set.
- @param other object to copy configuration from
- @since 7.0
*/
public void copyDefault(ProxyConfig other) {
Assert.notNull(other, "Other ProxyConfig object must not be null");
if (this.proxyTargetClass == null) {
this.proxyTargetClass = other.proxyTargetClass;
}
if (this.optimize == null) {
this.optimize = other.optimize;
}... //五个字段逐个"仅当本地没设过才继承"
}[framework] spring-aop/.../framework/ProxyConfig.java:167-186只有三态才能区分"⽤户显式设成了 false"和"⽤户压根没设过"。 boolean 做不到—— false 既可能是"我要 false",也可能是"我没管"。
copyDefault 服务的是 Framework 7 的"统⼀全局代理默认值"机制:容器⾥可以放⼀个专⻔的 ProxyConfig bean 当全局默认值,各个⾃动代理创建器在 setBeanFactory时把它捞出来合并:
/**
- ...
- @since 7.0
*/
static void applyDefaultProxyConfig(ProxyConfig proxyConfig, BeanFactory beanFactory) {
if (beanFactory.containsBean(DEFAULT_PROXY_CONFIG_BEAN_NAME)) {
ProxyConfig defaultProxyConfig = beanFactory.getBean(DEFAULT_PROXY_CONFIG_BEAN_NAME, ProxyConfig.class);
proxyConfig.copyDefault(defaultProxyConfig);
}
}[framework] spring-aop/.../framework/autoproxy/AutoProxyUtils.java:90-103 (常量 DEFAULT_PROXY_CONFIG_BEAN_NAME 在 :40-45 ,同样 @since 7.0 ;消费点在 AbstractAutoProxyCreator.java:186 )
🦴 ⼀个只有读源码才会撞⻅的⼩瑕疵:那个常量的 javadoc 第⼀⾏写的是——
/**
- The bean name of the internally managed auto-proxy creator.
- @since 7.0
*/
public static final String DEFAULT_PROXY_CONFIG_BEAN_NAME =
"org.springframework.aop.framework.autoproxy.defaultProxyConfig";AutoProxyUtils.java:40-45"内部管理的 auto-proxy creator 的 bean 名"——可它明明是 defaultProxyConfig ,⼀个 ProxyConfig 的 bean,不是 auto-proxy creator。 这是从隔壁AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME 复制过来时忘了改的⼀句。功能上毫⽆影响,但它是个很好的提醒:javadoc 是⼈写的,会过时、会串⾏。判断⾏为要看代码,注释只是线索。 这本书⾃始⾄终引 javadoc,就是因为它多数时候极其可靠——但"多数"不是"全部"。
本基线如此,这套东⻄在 Framework 6 / Boot 3 上是没有的。 与之配套的还有 @Proxyable 注解([framework] spring-context/.../context/annotation/Proxyable.java , @since 7.0 )和 ProxyType 枚举( DEFAULT / INTERFACES / TARGET_CLASS ),可以按单个 bean 指定代理类型,甚⾄⽤ @Proxyable(interfaces = ...) 限定只暴露哪⼏个接⼝。
框架⽂档对这条变化的描述是:
"As of 7.0, forcing a specific proxy type for individual beans is possible through the @Proxyable annotation on a given @Bean method or @Component class ...
For very specific purposes, you may even specify the proxy interface(s) to use through @Proxyable(interfaces=...) , limiting the exposure to selectedinterfaces rather than all interfaces that the target bean implements." —— [framework] framework-docs/.../core/aop/proxying.adoc:78-83这意味着⼀条流传多年的⽼结论在本基线上过期了:以前说"JDK 还是 CGLIB 只能全局⼆选⼀",现在可以按 bean 指定。写⽂章引⽤旧结论前,先看版本。
四、从⼀堆 Advisor 到⼀次真实调⽤:三段变身图纸有了,配置有了。⼀次真实的⽅法调⽤是怎么⾛完的?三段。
第⼀段:Advisor → 拦截器列表(装配期,可缓存)
@Override
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, @Nullable Class<?> targetClass) {...
for (Advisor advisor : advisors) {
if (advisor instanceof PointcutAdvisor pointcutAdvisor) {
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) { //① 类过滤
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
... match = mm.matches(method, actualClass); //② 静态⽅法匹配
if (match) {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor); //③ 适配成拦截器
if (mm.isRuntime()) {
for (MethodInterceptor interceptor : interceptors) {
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm)); //④ 延到运⾏期再判
}
}
else { interceptorList.addAll(Arrays.asList(interceptors)); }
}
}
}
else if (advisor instanceof IntroductionAdvisor ia) { /*只看 ClassFilter */ }else { /*⽆切点,直接加 */ }
}
return interceptorList;
}

[framework] spring-aop/.../framework/DefaultAdvisorChainFactory.java:58-112这段代码正好复述了前⾯所有的概念:两级过滤、 isRuntime() 分岔、Advisor 家族三分⽀。注意 config.isPreFiltered() 那个短路——⾃动代理创建器已经按⽬标类筛过⼀遍 advisor 了,运⾏期就不必再筛(这个开关来⾃ AbstractAutoProxyCreator.advisorsPreFiltered() ,默认 false, :520-522 ,由⼦类覆盖)。
动态匹配的那⼀⽀被包进⼀个包级 record,只有⼀⾏:
record InterceptorAndDynamicMethodMatcher(MethodInterceptor interceptor, MethodMatcher matcher) {
}[framework] spring-aop/.../framework/InterceptorAndDynamicMethodMatcher.java:32第⼆段:多形态 Advice → 单⼀ MethodInterceptor
public DefaultAdvisorAdapterRegistry() {
registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
registerAdvisorAdapter(new AfterReturningAdviceAdapter());
registerAdvisorAdapter(new ThrowsAdviceAdapter());
}[framework] spring-aop/.../framework/adapter/DefaultAdvisorAdapterRegistry.java:52-56三个适配器,把前置、返回后、抛异常后三种通知统统翻译成 MethodInterceptor 。⽽ MethodInterceptor 本身不需要适配——源码⾥那⾏注释很可爱:
if (advice instanceof MethodInterceptor) {// So well-known it doesn't even need an adapter.
return new DefaultPointcutAdvisor(advice);
}DefaultAdvisorAdapterRegistry.java:67-69设计意图:运⾏期只认⼀种东⻄—— MethodInterceptor 。 所有形态转换在装配期⼀次性做完,热路径上不做 instanceof 分⽀爆炸。这是"多形态输⼊、单形态执⾏"的经典收窄。
第三段: proceed() ——不是循环,是递归@Override
public @Nullable Object proceed() throws Throwable {// We start with an index of -1 and increment early.
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint(); //链尾 →真正调⽬标⽅法
}
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher dm) {// Evaluate dynamic method matcher here: static part will already have// been evaluated and found to match.
Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
if (dm.matcher().matches(this.method, targetClass, this.arguments)) { //★ 运⾏期动态匹配
return dm.interceptor().invoke(this);
}
else {// Dynamic matching failed.// Skip this interceptor and invoke the next in the chain.
return proceed();
}
}
else {
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}[framework] spring-aop/.../framework/ReflectiveMethodInvocation.java:155-181这段代码是整个 Spring AOP 的⼼跳。
注意:链不是被 for 循环遍历的。 是每个拦截器⾃⼰决定要不要往下⾛——它拿到 this (这个 MethodInvocation ),想继续就调 proceed() ,不想就直接返回。
于是:
@Around ⾥忘了调 proceed() → 整条链的后半段和⽬标⽅法永远不执⾏,⽅法返回 null,不报错。
事务拦截器可以在 proceed() 外⾯包 try/catch 决定提交还是回滚。
缓存拦截器可以在命中时根本不调 proceed() ,直接返回缓存值。
控制权在拦截器⼿⾥,不在框架⼿⾥。这是责任链模式最⼲净的⼀种实现。
链尾是 invokeJoinpoint() ( :189-191 ),最终落到 AopUtils.invokeJoinpointUsingReflection(...) ([framework] spring-aop/.../aop/support/AopUtils.java:351 )——⼀次普通的反射调⽤。壳的全部魔法,到这⼀步就结束了。
索引 currentInterceptorIndex 存在 invocation 对象上,⽽ invocation 每次调⽤都 new ⼀个,所以天然线程安全。需要重⼊(同⼀次调⽤把链再跑⼀遍)时⽤invocableClone() 复制⼀份独⽴索引( :203-221 )。
✨ 顺带看⼀个双档缓存的⼩设计。 每次调⽤都要拿拦截器链,这是最热的路径:
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
List<Object> cachedInterceptors;
if (this.methodCache != null) {// Method-specific cache for method-specific pointcuts
MethodCacheKey cacheKey = new MethodCacheKey(method);
cachedInterceptors = this.methodCache.get(cacheKey);...
}
else {
// Shared cache since there are no method-specific advisors (see below).
cachedInterceptors = this.cachedInterceptors;...
}
return cachedInterceptors;
}AdvisedSupport.java:516-538配了⽅法级切点 → ⽤ ConcurrentHashMap 按⽅法缓存;⼀个 PointcutAdvisor 都没有 → 所有⽅法共⽤同⼀个 cachedInterceptors 列表,连 map 查找都省了。这个档位在 adviceChanged() ⾥拨( :543-556 ):遍历 advisor,只要发现⼀个 PointcutAdvisor 就建 map,⼀个都没有就退化成共享 List。
代价:任何⼀次 addAdvisor / removeAdvisor / addInterface 都会把三层缓存全部清空。 运⾏期动态改 advisor 是很贵的操作,别在热路径上⼲。
五、与 AspectJ 的分野:不是简化版,是另⼀条路回到开篇的三条边界,现在可以和 AspectJ 摆在⼀起对照了。
维度 Spring AOP(本基线 7.1.0-SNAPSHOT) AspectJ织⼊时机 运⾏时⽣成代理 编译期( ajc )/ 加载期(LTW agent)
连接点 仅⽅法执⾏ ⽅法 / 构造器 / 字段读写 / 异常处理 / 静态初始化…作⽤对象 仅 Spring 容器 bean(或你⼿⼯ ProxyFactory 的对象) 任意对象,含 domain object⾃调⽤ 绕过增强 正常增强final / private ⽅法 不能增强 可以需要额外编译 / agent 否 是this / target 区分(代理 / ⽬标) 相同依赖 aspectjweaver 是 optional,只⽤其表达式解析 必须 weaver选型判据⽂档给得很⼲脆,可以直接背下来:
"If you only need to advise the execution of operations on Spring beans, Spring AOP is the right choice. If you need to advise objects not managed by the Spring
container (such as domain objects, typically), you need to use AspectJ. You also need to use AspectJ if you wish to advise join points other than simple method
executions (for example, field get or set join points and so on)." —— [framework] framework-docs/.../core/aop/choosing.adoc:16-21⽽ Spring 团队⾃⼰对这个关系的定位,我认为是全份⽂档⾥最有⻛度的⼀段:
"Spring AOP never strives to compete with AspectJ to provide a comprehensive AOP solution. We believe that both proxy-based frameworks such as Spring AOPand full-blown frameworks such as AspectJ are valuable and that they are complementary, rather than in competition." —— [framework] framework-docs/.../core/aop/introduction-spring-defn.adoc:27-30两处最容易被咬的差异,单独拎出来。
其⼀,⽩名单只有 10 个原语。 Spring ⽀持的 AspectJ 原语是⼀份硬编码在源码⾥的⽩名单:
private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = Set.of(PointcutPrimitive.EXECUTION,PointcutPrimitive.ARGS,PointcutPrimitive.REFERENCE,PointcutPrimitive.THIS,PointcutPrimitive.TARGET,PointcutPrimitive.WITHIN,PointcutPrimitive.AT_ANNOTATION,PointcutPrimitive.AT_WITHIN,PointcutPrimitive.AT_ARGS,
PointcutPrimitive.AT_TARGET);[framework] spring-aop/.../aop/aspectj/AspectJExpressionPointcut.java:88-98⽩名单之外的那些,⽂档逐个点了名—— call 、 get 、 set 、 preinitialization 、 staticinitialization 、 initialization 、 handler 、 adviceexecution 、withincode 、 cflow 、 cflowbelow 、 if 、 @this 、 @withincode ——⽤了直接抛 IllegalArgumentException ([framework] framework-docs/.../core/aop/ataspectj/pointcuts.adoc:76-81 )。
顺⼿数⼀遍:这份名单是 14 个,不是很多⽂章⾥写的 13 个。 我数了三遍,因为最后两个 @this 和 @withincode 前⾯隔着⼀个 and ,很容易在扫读时并成⼀个。这种地⽅最好⾃⼰数——转述的次数越多,数字越不可靠。
看看这份名单: get / set 是字段读写, call 是调⽤⽅那⼀侧, cflow 是控制流。全部要求改字节码。代理做不到。 这不是 Spring 偷懒,是物理限制。
(顺带:这条⾄少是响亮地失败的,抛异常⽽不是静默忽略。这⼀处 Spring 做对了。)
其⼆, this 和 target 在两边语义不同。
"AspectJ itself has type-based semantics and, at an execution join point, both this and target refer to the same object: the object executing the method.
Spring AOP is a proxy-based system and differentiates between the proxy object itself (which is bound to this ) and the target object behind the proxy(which is bound to target )." —— [framework] framework-docs/.../core/aop/ataspectj/pointcuts.adoc:87-93源码⾥的绑定动作有⼀段注释可以佐证:
// Bind Spring AOP proxy to AspectJ "this" and Spring AOP target to AspectJ target,// consistent with return of MethodInvocationProceedingJoinPoint[framework] spring-aop/.../aop/aspectj/AspectJExpressionPointcut.java:349-362 附近同⼀个 AspectJ 表达式,在 Spring AOP 和原⽣ AspectJ 下语义不同。 从 Spring AOP 迁到 LTW,或者反过来,这是⼀颗隐形地雷。
🦴 ⻣灰级细节
1. AdvisorKeyEntry ——⽤切点的 toString() 当指纹,省 metaspace。Framework 6.0.10 加了⼀个东⻄:把 advisor 列表"降维"成⼀串只保留 key 的桩对象:
public AdvisorKeyEntry(Advisor advisor) {
this.adviceType = advisor.getAdvice().getClass();
if (advisor instanceof PointcutAdvisor pointcutAdvisor) {
Pointcut pointcut = pointcutAdvisor.getPointcut();
this.classFilterKey = pointcut.getClassFilter().toString(); //★ 靠 toString!
this.methodMatcherKey = pointcut.getMethodMatcher().toString();
}...
}@Override
public Advice getAdvice() {
throw new UnsupportedOperationException();
}[framework] spring-aop/.../framework/AdvisedSupport.java:707-745 ( @since 6.0.10 , :703 )
⼀个只为当缓存 key ⽽存在的 Advisor,连 getAdvice() 都直接抛异常——它压根不打算被当成真 advisor ⽤。⽬的:让"advice 类型 + 切点字符串"相同的多个 bean 复⽤同⼀个⽣成的代理类,省 metaspace 和类加载时间。
代价藏在另⼀处。 MethodMatcher 和 ClassFilter 的 javadoc ⾥各有⼀段⼀模⼀样的加粗 WARNING:
"WARNING: Concrete implementations of this interface must provide proper implementations of equals() , hashCode() , and toString() in order to allow the
matcher to be used in caching scenarios — for example, in proxies generated by CGLIB. As of Spring Framework 6.0.13, the toString() implementation must
generate a unique string representation that aligns with the logic used to implement equals() ." —— [framework] spring-aop/.../aop/MethodMatcher.java:46-53 ( ClassFilter.java:26-33 同⽂)
看到那个 "As of 6.0.13" 了吗?6.0.10 引⼊优化,6.0.13 加固约束——这是⼀次性能优化引⼊正确性⻛险后的补救。
切点的 toString() ⼀旦不唯⼀,两个本不相⼲的切⾯就会共⽤同⼀个⽣成的代理类,增强会串味。 你⾃⼰写 Pointcut 实现时,如果只重写了 equals / hashCode 忘了toString ,恭喜,你踩上了。
- hasUserSuppliedInterfaces() ——"没有接⼝就⽤ CGLIB"这句话不够准确。
boolean hasUserSuppliedInterfaces() {
for (Class<?> ifc : this.interfaces) {
if (!SpringProxy.class.isAssignableFrom(ifc) && !isAdvisorIntroducedInterface(ifc)) {
return true;
}
}
return false;
}[framework] spring-aop/.../framework/AdvisedSupport.java:268-275它排除掉了框架⾃加的标记接⼝( SpringProxy )和引介带进来的接⼝。所以准确的说法是:"没有⽤户提供的业务接⼝才⾛ CGLIB 分⽀"。⼀个只被 IntroductionAdvisor加了接⼝的 bean,在这⾥依然算"没有接⼝"。
- MethodCacheKey 在构造时就把 hashCode 预算好。
内部 final class,构造时存下 method.hashCode() , equals 先⽐引⽤再⽐对象( AdvisedSupport.java:661 )。热路径上的微优化——每次⽅法调⽤都要⽤这个 key 查⼀次 map,省⼀次 hashCode 计算是有意义的。
- ExposeInvocationInterceptor 会⾃动插到队⾸。
只要链⾥出现了 AspectJ 通知,就会在第 0 位插⼀个拦截器,把当前 invocation 放进 ThreadLocal :
if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {
advisors.add(0, ExposeInvocationInterceptor.ADVISOR);
return true;
}[framework] spring-aop/.../aop/aspectj/AspectJProxyUtils.java:61-64它是 args() 、 this() 、 target() 这些运⾏期切点能拿到实参和代理引⽤的前提。你的拦截器链⾥永远有⼀个你没写过的成员——调试时看到链⻓度⽐ advisor 数多 1,别惊讶。
- ⼀个逃⽣开关: spring.aop.ajc.ignore 。
/**
- System property that instructs Spring to ignore ajc-compiled aspects
- for Spring AOP proxying, restoring traditional Spring behavior for
- scenarios where both weaving and AspectJ auto-proxying are enabled.
* <p>The default is "false". Consider switching this to "true" if you- encounter double execution of your aspects in a given build setup.
- ...
- @since 6.1.15
*/
public static final String IGNORE_AJC_PROPERTY_NAME = "spring.aop.ajc.ignore";[framework] spring-aop/.../aop/aspectj/annotation/AbstractAspectJAdvisorFactory.java:65-75同⼀个切⾯,被 ajc 织进了字节码,⼜被 Spring ⾃动代理挂了⼀遍 → 执⾏两次。 @since 6.1.15 说明这是个后加的补丁。javadoc 还带⼀句劝告:"we recommendrestructuring your AspectJ configuration to avoid such double exposure to begin with"——这开关是⽌⾎带,不是解决⽅案。
- Spring AOP 明确拒绝两种 AspectJ 实例化模型。
if (ajType.getPerClause().getKind() == PerClauseKind.PERCFLOW) {
throw new AopConfigException(aspectClass.getName() + " uses percflow instantiation model: " +
"This is not supported in Spring AOP.");
}
if (ajType.getPerClause().getKind() == PerClauseKind.PERCFLOWBELOW) { ... }[framework] spring-aop/.../aop/aspectj/annotation/AbstractAspectJAdvisorFactory.java:99-106percflow / percflowbelow 需要跟踪控制流,代理模型看不到控制流。这⾥也是响亮地抛异常,不是静默。
⚠ 暗礁清单
- ⾃调⽤绕过增强——头号问题。 this.method() ⾛的是原件⾃⼰的⽅法表( proxying.adoc:210-216 )。三条出路的官⽅推荐顺序是:重构掉 → ⾃注⼊ →
AopContext.currentProxy() (最后这条⽂档原话是 "highly discouraged, and we hesitate to point it out", :229 )。第三条还要求 exposeProxy=true ,⽽AopContext 的类 javadoc ⾃陈:"Spring's AOP framework does not expose proxies by default, as there is a performance cost in doing so"([framework]spring-aop/.../framework/AopContext.java:31-32 )。
- final / private / 包私有⽅法⽆法增强( proxying.adoc:17-21 )——CGLIB 靠继承重写,重写不了就增强不了。
3. addAdvice(advice) 默认 Pointcut.TRUE ,连 toString() 都会被拦( Advised.java:186-188 )。
4. 默认 opaque=false :任何⼈都能 ((Advised) bean).removeAdvisor(0) ( ProxyConfig.java:96-97 )。- 切点 toString() 不唯⼀ → 代理类缓存错误复⽤( MethodMatcher.java:46-53 )。
- 动态切点( args() 等)每次调⽤都重新匹配( MethodMatcher.java:37-44 )。
- canApply 在装配期遍历⽬标类及其全部接⼝的全部声明⽅法([framework] spring-aop/.../aop/support/AopUtils.java:239-274 )——每个候选 advisor × 每个bean × 每个⽅法。这是启动慢的⼀个真实来源,⽐代理⽣成本身贵得多。
- this / target 语义与原⽣ AspectJ 不同( pointcuts.adoc:87-93 )——迁移地雷。
- @After 的执⾏顺序与排序表相反( ReflectiveAspectJAdvisorFactory.java:81-85 )。
10. optimize=true 会跳过 final ⽅法校验( ProxyConfig.java:77-80 )——名字骗⼈,别开。🎯 三句带⾛
1. Advisor = Pointcut + Advice ,这是框架内部唯⼀认的单位。 你写 @Aspect 、XML、 MethodInterceptor 、 MethodBeforeAdvice ,最终全部收敛成
AdvisedSupport.advisors 这⼀个 List<Advisor> ([framework] spring-aop/.../framework/AdvisedSupport.java:106 ); Aspect 在运⾏期没有对应的Java 类型,⼀个 @Aspect 类在装配期被拆成 N 个 Advisor。
- 三条边界:只做⽅法级、只对容器管理的 bean ⽣效、基于运⾏时代理⽽⾮字节码织⼊。 依据分别是——⽂档 "a join point always represents a methodexecution"( introduction-defn.adoc:13-15 )+ ConstructorInterceptor 在 org.springframework 下零引⽤; AbstractAutoProxyCreator implementsSmartInstantiationAwareBeanPostProcessor ( :96-97 ); aspectjweaver 是 optional 依赖( spring-aop.gradle:10 ),Spring 只借表达式解析器。
- ProxyFactory 是⻔⾯, AdvisedSupport 才是⼼脏, ProxyConfig 的五个开关默认全 false。 本基线(Framework 7.1.0-SNAPSHOT)把这五个字段从 boolean
改成了三态 @Nullable Boolean ( ProxyConfig.java:39-47 ),就是为了让 copyDefault(...) ( @since 7.0 , :167-186 )能区分"显式设了 false"和"压根没设"——这是 7.0 统⼀全局代理默认值与 @Proxyable 的地基,6/3 时代没有这套东⻄。
承上启下到这⾥,"壳"的抽象层⾯已经讲完了:⼯序(Advice)刻在哪些位置(Pointcut),打包成⼀整套(Advisor),由 AdvisedSupport 这张图纸持有,最后交给某个 AopProxy 去做成⼀个实物。
注意最后那半句⾥的"某个"。
ProxyCreatorSupport.createAopProxy() 那⼀⾏—— return getAopProxyFactory().createAopProxy(this) ——把整份配置交了出去,交给了DefaultAopProxyFactory 。⽽那个⼯⼚做的第⼀件事,是⼀个⼆选⼀:
if (config.isOptimize() || config.isProxyTargetClass() || !config.hasUserSuppliedInterfaces()) {...
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}照榫卯⼝另做⼀个同规格的壳,还是照原件仿造⼀个⼦件?
这个⼆选⼀决定了太多东⻄:你能不能按具体类注⼊、 final ⽅法会不会被静默跳过、构造器会不会被调⽤两次、堆栈⾥会多出⼏层什么名字。⽽最要命的是——这个选择的默认值,在裸 Framework 和在 Spring Boot ⾥是相反的。框架⽂档⾃⼰承认了这件事:
"The global default proxy type may differ between setups. While the core framework suggests interface-based proxies by default, Spring Boot may — dependingon configuration properties — enable class-based proxies by default." —— [framework] framework-docs/.../core/aop/proxying.adoc:74-76⼀句"may differ between setups",背后是多少个"本地能跑、换个环境 ClassCastException "的深夜。
下⼀章,我们把这两种壳拆开看:JDK 动态代理和 CGLIB 各⾃是怎么把⼀个对象仿造出来的,那个默认值到底在两个仓库的哪⼀⾏被定死,以及为什么 final 是它们共同的天花板。