第22章 卷六 · 套壳 · 刻在哪些位置:Pointcut 与表达式
刻在哪些位置:Pointcut 与表达式"我读得懂 AspectJ 的每⼀句话。但我这辈⼦没碰过⼀个字节码。" —— AspectJExpressionPointcut 的⾃述开场:⼀⾏字符串,谁在读它?
你在某个 @Aspect 类⾥写下这么⼀⾏:
@Pointcut("execution(* com.example.service.*Service.*(..)) && args(id, ..)")这是⼀⾏字符串。它不是 Java 表达式,不是注解元数据,编译器完全不看它⼀眼—— javac 眼⾥它跟 "hello" 没有区别。可到了运⾏时,坊⾥居然能凭这⾏字,从上千件器⾥精确挑出该刻⼯序的那⼏件,还能把第⼀个参数按名字送进你的通知⽅法。
那么问题来了:谁把这⾏字读懂的?
答案是 AspectJ。但请⽴刻把下⼀个念头掐掉——AspectJ 在这⾥没有做织⼊。上⼀章我们讲了"壳上刻的是什么⼯序"(Advice),这⼀章讲"刻在哪些位置"(Pointcut)。⽽位置的判定权,Spring 借了 AspectJ 的嘴,却没借它的⼿。
这个区分,是本章要点破的第⼀件事,也是很多⼈搞混⼀辈⼦的⼀件事。
⼀、"只借表达式,不做织⼊":三条可核对的物证物证⼀:这个依赖是 optional 的// [framework] spring-aop/spring-aop.gradle:5-12
dependencies {
api(project(":spring-beans"))
api(project(":spring-core"))
compileOnly("com.google.code.findbugs:jsr305") // for the AOP Alliance fork
optional("org.apache.commons:commons-pool2")
optional("org.aspectj:aspectjweaver")
optional("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")...
}
注意那⾏ optional("org.aspectj:aspectjweaver") ( [framework] spring-aop/spring-aop.gradle:10 )——不是 api ,不是 implementation ,是 optional。这⼀个词就把话说尽了:没有 aspectjweaver.jar,spring-aop 照样跑。 Pointcut 、 ClassFilter 、 MethodMatcher 、 ProxyFactory 、整套代理机制,⼀个字节都不依赖AspectJ。只有当你要写 execution(...) 这种字符串时,才需要把那个 jar 拽进来当解析器⽤。
⼀个真正做织⼊的框架,绝⽆可能把织⼊器标成 optional。
Boot 那边对这个 optional 的处理⼲净得像⼿术:⽤类在不在决定⾛哪条路。
// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java:50-73
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Advice.class) // org.aspectj.weaver.Advice
static class AspectJAutoProxyingConfiguration { ... }
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingClass("org.aspectj.weaver.Advice")
@ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", matchIfMissing = true)
static class ClassProxyingConfiguration { ... }
顺⼿把⼀个必须点明的默认值坐实(硬纪律④):Boot 侧的 CglibAutoProxyConfiguration 标的是 @ConditionalOnBooleanProperty(name = "spring.aop.proxy-
target-class", matchIfMissing = true) + @EnableAspectJAutoProxy(proxyTargetClass = true) ( [boot] .../AopAutoConfiguration.java:61-66 )——Boot

默认⾛ CGLIB,⽽ Framework 侧 @EnableAspectJAutoProxy ⾃⼰的默认是 proxyTargetClass = false 。这是 Boot 主动翻转过的默认值,别把两边的说法混着背。
(另: spring.aop.auto 缺省即开, :47 ;本基线这⾥⽤的是 Boot 4 的新式 @ConditionalOnBooleanProperty ,且 AopAutoConfiguration 已是 public finalclass , :48 。)
物证⼆:全场只调三个⽅法Spring 对 AspectJ 的全部索求,落在三个调⽤上:
问什么 调的 AspectJ ⽅法 坐标(均为 AspectJExpressionPointcut.java )
这个类⾥有可能有连接点吗 PointcutExpression.couldMatchJoinPointsInType(Class) :285
这个⽅法的 execution 匹配吗 PointcutExpression.matchesMethodExecution(Method) :479
这次实际调⽤匹配吗 ShadowMatch.matchesJoinPoint(this, target, args) :373全是 org.aspectj.weaver.tools.* 这个公开⼯具包⾥的东⻄。解析⼊⼝更是只有⼀个类:
// [framework] spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java:242-248
private PointcutParser initializePointcutParser(@Nullable ClassLoader classLoader) {
PointcutParser parser = PointcutParser
.getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(
SUPPORTED_PRIMITIVES, classLoader);
parser.registerPointcutDesignatorHandler(new BeanPointcutDesignatorHandler());
return parser;
}PointcutParser ——解析器。没有 Weaver ,没有 BcelWorld ,没有 ClassPreProcessor 。Spring 要的是判决书,不是施⼯队。
类头 javadoc ⾃⼰也承认了这条边界:
"Spring Pointcut implementation that uses the AspectJ weaver to evaluate a pointcut expression. … Naturally, as this is to be processed by Spring AOP'sproxy-based model, only method execution pointcuts are supported." —— [framework] .../AspectJExpressionPointcut.java:64-65, 70-71物证三:那份"不⽀持清单"
参考⽂档⽩纸⿊字列了 Spring 不⽀持的指示符:
"The full AspectJ pointcut language supports additional pointcut designators that are not supported in Spring: call , get , set , preinitialization ,staticinitialization , initialization , handler , adviceexecution , withincode , cflow , cflowbelow , if , @this , and @withincode ." ——[framework] framework-docs/modules/ROOT/pages/core/aop/ataspectj/pointcuts.adoc:76-81把这份名单读⼀遍,你会发现它们有⼀个共同点:
call —— 切调⽤点(在调⽤⽅那⼀侧插桩);
get / set —— 切字段读写;
staticinitialization / preinitialization —— 切类/对象初始化;
cflow / cflowbelow —— 切控制流("在 A 的调⽤链之内");
handler —— 切 catch 块。
全都是代理做不到、只有改字节码才做得到的地⽅。 ⼀个壳只能拦住"从外⾯打进来的⽅法调⽤"——它拦不住你读⼀个字段,拦不住你在⽅法体⾥ new ⼀个对象,更拦不住"某次调⽤发⽣在谁的控制流⾥"。所以这份不⽀持清单不是功能缺失,它就是"代理模型"这四个字的物理边界。
代码侧的⽩名单与⽂档严丝合缝:
// [framework] .../AspectJExpressionPointcut.java:88-98
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);⼗个。⽽⽂档那份"⽀持的 PCD"清单( pointcuts.adoc:52-72 )数下来是九个: execution 、 within 、 this 、 target 、 args 、 @target 、 @args 、 @within 、@annotation 。差的那⼀个是 REFERENCE ——它不描述"切哪⼉",⽽是"引⽤另⼀个具名切点"的能⼒(类头 javadoc :67-68 说 "This can reference other pointcuts and
use composition")。所以你能写 @Pointcut("anyService() && args(id)") 复⽤切点,靠的就是这⼀票。还有⼀件更值得注意的事: bean() ⼀个⽩名单席位都没占。它根本不是 primitive,⾛的是 parser.registerPointcutDesignatorHandler(...) 这个扩展⼝。这条线索后⾯会成为本章最有意思的⼀段(⻅第七节)。
⚠ 暗礁(第⼀处,也是本章第⼀个批评):⽂档说⽤了不⽀持的 PCD 会抛 IllegalArgumentException 。代码⾥这个异常被吞了。 详⻅第四节——它只落⼀⾏
logger.debug ,对外表现为"这个切点谁都不匹配"。⽂档与实现在这⾥不⼀致,⽽受害的是排查问题的你。
⼆、⼀个对象,三张脸
Pointcut 这个接⼝的 javadoc 只有⼀句核⼼话:
"A pointcut is composed of a ClassFilter and a MethodMatcher ." —— [framework] spring-aop/src/main/java/org/springframework/aop/Pointcut.java:22即 Pointcut = ClassFilter × MethodMatcher:先问"这个类要不要看",再问"这个⽅法要不要刻"。两个正交的维度,两个独⽴接⼝,教科书式的分解。
然后看 AspectJExpressionPointcut 怎么实现它:
// [framework] .../AspectJExpressionPointcut.java:83-84public class AspectJExpressionPointcut extends AbstractExpressionPointcut
implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware {// [framework] .../AspectJExpressionPointcut.java:170-180@Override
public ClassFilter getClassFilter() {
checkExpression();
return this;
}@Override
public MethodMatcher getMethodMatcher() {
checkExpression();
return this;
}两个 getter 都返回 this 。
第⼀眼像偷懒,其实是这套设计⾥最诚实的⼀笔。因为 execution(* com.foo.Bar.baz(..)) 这⾏字⾥,"类型部分"和"⽅法部分"来⾃同⼀棵语法树——它们本来就拆不开。你没法把这个表达式劈成"⼀个只管类的对象"和"⼀个只管⽅法的对象",那样得解析两遍、维护两份状态。
所以 Spring 让同⼀个对象戴三顶帽⼦,共享同⼀份 PointcutExpression 。所谓"两级过滤",在这⾥不是两个组件,⽽是对同⼀棵语法树问两种粒度的问题。
⽽这个"粒度"的差别,藏在 AspectJ 那个⽅法名⾥:
couldMatchJoinPointsInType(Class)^^^^^could。 类级永远只能给"有可能",绝不会给"⼀定"。这个"三态"——YES / NO / MAYBE——是理解整套匹配机制的钥匙,接下来每⼀节都绕着它转。
顺带⼀提,这个类的字段清单也很能说明问题:
// [framework] .../AspectJExpressionPointcut.java:112-116
private transient volatile @Nullable ClassLoader pointcutClassLoader;
private transient volatile @Nullable PointcutExpression pointcutExpression;
private transient volatile boolean pointcutParsingFailed;三个 transient volatile 。 transient 是因为 PointcutExpression 是 AspectJ 的内部对象、不可序列化,⽽这个切点⾃⼰是要能序列化的——所以解析必须是惰性的,反序列化之后靠 obtainPointcutExpression() 就地重建。 volatile 是因为匹配发⽣在容器多线程创建 bean 的过程中。
三、九个指示符,各切在哪⼀⼑把⽂档那份清单( pointcuts.adoc:52-72 )翻成⼈话,顺带标出每个指示符在 Spring 代理模型下的真实语义:
指示符 切什么 需要看运⾏时吗execution(...) ⽅法执⾏本身——签名匹配。Spring AOP 的主⼒,九成场景只⽤它 否within(com.foo..*) ⽅法声明在哪些类型⾥。粗粒度、纯静态,最便宜 否this(Type) 代理对象是不是 Type 的实例 可能target(Type) 被代理的原件是不是 Type 的实例 可能
args(String, ..) 实参的类型 是@within(Anno) ⽅法所在类型上有没有这个注解 否@annotation(Anno) ⽅法上有没有这个注解 可能@target(Anno) 原件的运⾏时类上有没有这个注解 可能@args(Anno) 实参的运⾏时类型上有没有这个注解 是其中 this 与 target 是 Spring 与原⽣ AspectJ 的语义分歧点,⽂档专⻔写了⼀段:
"AspectJ itself has type-based semantics and, at an execution join point, both this and target refer to the same object… 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] .../pointcuts.adoc:89-93在原⽣ AspectJ ⾥,⽅法执⾏点上 this 和 target 是同⼀个对象——因为织⼊之后压根没有第⼆个对象。到了 Spring,有壳有原件,于是 this 绑壳、 target 绑原件。
代码⾥那⾏注释把这条约定写得清清楚楚:
// [framework] .../AspectJExpressionPointcut.java:349-350// Bind Spring AOP proxy to AspectJ "this" and Spring AOP target to AspectJ target,// consistent with return of MethodInvocationProceedingJoinPoint
⚠ 暗礁:从原⽣ AspectJ ⼯程迁到 Spring AOP 的切点, this(...) 的含义会静默改变。尤其在 JDK 动态代理下——壳只实现接⼝,所以 this(YourConcreteClass) 对壳
来说是 false,⽽在 AspectJ ⾥它本该是 true。这不会报错,只会不⽣效。
四、第⼀级过滤:ClassFilter 的五重防御启动期每个 bean 都要过这⼀关。这是整个 AOP 启动性能的命⻔,也是⼀段写得极密的代码:
// [framework] .../AspectJExpressionPointcut.java:272-306@Override
public boolean matches(Class<?> targetClass) {
if (this.pointcutParsingFailed) {
// Pointcut parsing failed before below -> avoid trying again.
return false; //①
}
if (this.aspectCompiledByAjc && compiledByAjc(targetClass)) {
// ajc-compiled aspect class for ajc-compiled target class -> already weaved.
return false; //②
}
try {
try {
return obtainPointcutExpression().couldMatchJoinPointsInType(targetClass); //③
}
catch (ReflectionWorldException ex) {
logger.debug("PointcutExpression matching rejected target class - trying fallback expression", ex);
PointcutExpression fallbackExpression = getFallbackPointcutExpression(targetClass);
if (fallbackExpression != null) {
return fallbackExpression.couldMatchJoinPointsInType(targetClass); //④
}
}
}
catch (IllegalArgumentException | IllegalStateException | UnsupportedPointcutPrimitiveException ex) {
this.pointcutParsingFailed = true; //⑤
if (logger.isDebugEnabled()) {
logger.debug("Pointcut parser rejected expression [" + getExpression() + "]: " + ex);
}
}
catch (Throwable ex) {
logger.debug("PointcutExpression matching rejected target class", ex);
}
return false;
}层②是全篇最有意思的⼀段。 compiledByAjc ⼲的事是——翻字段名:
// [framework] .../AspectJExpressionPointcut.java:86, 541-549
private static final String AJC_MAGIC = "ajc$";
private static boolean compiledByAjc(Class<?> clazz) {
for (Field field : clazz.getDeclaredFields()) {
if (field.getName().startsWith(AJC_MAGIC)) {
return true;
}
}
Class<?> superclass = clazz.getSuperclass();
return (superclass != null && compiledByAjc(superclass));
}ajc(AspectJ 的编译器)真做织⼊时,会往类⾥塞⼀堆 ajc$ 前缀的合成字段。Spring 就靠嗅这个前缀判断"这个类已经被⼈织过了"。触发条件是两个都成⽴:切⾯是 ajc 编译的、⽬标类也是 ajc 编译的——那就别再套⼀层壳,否则同⼀道⼯序会⾛两遍。
这⼀层守卫的存在,本身就是"只借表达式不做织⼊"的反向证词:Spring 知道⾃⼰不是唯⼀可能动这个类的⼈,所以要看看别⼈是不是先动过了。 它承认混合模式存在,只是要避开重叠。
(成本上也很克制: aspectCompiledByAjc 是在 setPointcutDeclarationScope 时对切⾯类算⼀次就存下来的( :145-148 ),绝⼤多数应⽤⾥常年是 false , && 短路,后⾯那趟全类层次的反射扫描根本不会触发。)
⚠ 静默失效:⽂档说抛异常,代码把它吞了
看层⑤。 UnsupportedPointcutPrimitiveException ——就是你写了 call(...) 、 cflow(...) 这些不⽀持的 PCD 时 AspectJ 抛出来的东⻄。⽂档承诺"results in anIllegalArgumentException being thrown",实际发⽣的是:
1. 置 pointcutParsingFailed = true ;- 打⼀⾏ DEBUG ⽇志;
- return false 。
于是对外表现为"这个切点不匹配任何类"。测试直接把这个⾏为钉死了:
// [framework] spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java:265-269@Test
void withUnsupportedPointcutPrimitive() {
String expression = "call(int org.springframework.beans.testfixture.beans.TestBean.getAge())";
assertThat(getPointcut(expression).getClassFilter().matches(Object.class)).isFalse();
}
isFalse() ,不是 assertThatThrownBy 。⽽且层①那个熔断标志是永久的:⼀旦失败过⼀次,往后所有类的匹配都直接 return false ,连试都不试。
这是本章我要给出的最重的⼀处批评:⼀个写错的切点,在⽣产环境⾥的表现是"我的切⾯完全没⽣效",⽽线索只在 DEBUG ⽇志⾥。 不开 DEBUG,你能拿到的信息量是零——没有警告、没有启动失败、没有任何 actuator 端点告诉你"有个切点被判死刑了"。这条设计选择了"不因为⼀个坏切点炸掉整个应⽤"的鲁棒性,代价是把排查成本全额转嫁给了使⽤者。考虑到 pointcutParsingFailed 本来就是⼀次性熔断(每个切点最多打⼀⾏⽇志,不存在刷屏⻛险),这⾥完全有条件打 WARN ⽽不是 DEBUG。
(另⼀处相关的粗糙: and / or / not 到 && / || / ! 的转换是纯字符串替换—— StringUtils.replace(pcExpr, " and ", " && ") , :257-262 。存在的理由很实在:XML ⾥写 && 要转义成 && 。但它就是个 replace ,谁也没保证⽅法名或包名⾥不会碰巧出现 " and "。测试证明了它的正向⾏为( AspectJExpressionPointcutTests.java:271-276 ),没有覆盖误伤场景。同样的替换逻辑在 TypePatternClassFilter.java:114-118 ⾥还抄了⼀份。)
五、第⼆级过滤:MethodMatcher 与那个致命的 MAYBE类过了,轮到⽅法。
// [framework] .../AspectJExpressionPointcut.java:308-333@Override
public boolean matches(Method method, Class<?> targetClass, boolean hasIntroductions) {
ShadowMatch shadowMatch = getTargetShadowMatch(method, targetClass);// Special handling for this, target, @this, @target, @annotation// in Spring - we can optimize since we know we have exactly this class,// and there will never be matching subclass at runtime.
if (shadowMatch.alwaysMatches()) {
return true;
}
else if (shadowMatch.neverMatches()) {
return false;
}
else {// the maybe case
if (hasIntroductions) {
return true;
}// A match test returned maybe - if there are any subtype sensitive variables
// involved in the test (this, target, at_this, at_target, at_annotation) then// we say this is not a match as in Spring there will never be a different// runtime subtype.
RuntimeTestWalker walker = getRuntimeTestWalker(shadowMatch);
return (!walker.testsSubtypeSensitiveVars() || walker.testTargetInstanceOfResidue(targetClass));
}
}AspectJ 交回来的 ShadowMatch 是⼀份三态判决书: alwaysMatches() (必中)、 neverMatches() (必不中)、 maybeMatches() (得看运⾏时)。前两态直接照办,全部的智慧都在第三态。
hasIntroductions == true 就直接放⾏第⼀个分⽀只有⼀⾏:有 introduction,maybe ⼀律当 true。
为什么?因为 introduction( @DeclareParents ,给⼀件器凭空加上它⾃⼰没声明过的接⼝)会让⽬标对象在运⾏时多出静态类型信息⾥没有的类型。这时候拿"我看到的类声明"去否决 target(SomeIntroducedType) ,是不安全的——那个类型确实会出现,只是不写在 .class ⾥。
这是"静态优化必须对动态语义保守"的教科书式体现:拿不准就放⾏,让运⾏时再判⼀次。
反过来:Spring 敢把 target(TYPE) 就地判死else ⾥那⼀句才是真的狠:
return (!walker.testsSubtypeSensitiveVars() || walker.testTargetInstanceOfResidue(targetClass));注释解释得⼲净利落( :326-329 ):残式⾥如果涉及 this / target / @this / @target / @annotation 这些"对⼦类型敏感"的变量,那就直接判不匹配,理由是——"…as in Spring there will never be a different runtime subtype."
在真正的 AspectJ 织⼊⾥,⼀个 execution shadow 可以被任意⼦类继承、以⼦类的身份执⾏,所以 target(Sub) 必须留到运⾏时才知道。但在 Spring 的代理模型⾥,壳是为某⼀个具体的 bean 类打造的,原件的运⾏时类型就是建壳那⼀刻的那个类,不可能中途变成别的⼦类。 于是这条在 AspectJ ⾥必须动态的判定,在 Spring ⾥可以在启动期就拍板。
这是⼀次合法的抄近道——不是偷⼯减料,是因为模型更受限,所以能推出更强的结论。
✨ 顺带注意:这两个分⽀的⽅向恰好相反。有 introduction 时"宁可放⾏",遇到⼦类型敏感变量时"宁可拒绝"。因为它们服务的是同⼀个流程的两端:前者怕误杀(漏了该切
的),后者怕滥建(给不该切的类建壳)。各⾃守住⾃⼰那⼀侧的安全边界。
🦴 ⻣灰级细节:Spring 是怎么"看⻅"残式的
问题来了—— walker.testsSubtypeSensitiveVars() 是怎么知道"AspectJ 打算在运⾏时测哪些变量"的?
ShadowMatch 的公开 API ⾥没有这个⽅法。
于是有了 RuntimeTestWalker 。它的类头 javadoc 不是⽂档,是⼀封道歉信:
// [framework] spring-aop/src/main/java/org/springframework/aop/aspectj/RuntimeTestWalker.java:44-58/**
- This class encapsulates some AspectJ internal knowledge that should be
- pushed back into the AspectJ project in a future release.
*
* <p>It relies on implementation specific knowledge in AspectJ to break- encapsulation and do something AspectJ was not designed to do: query
- the types of runtime tests that will be performed. The code here should
* migrate to {@code ShadowMatch.getVariablesInvolvedInRuntimeTest()}- or some similar operation.
*
* <p>See <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=151593">Bug 151593</a>*
- @author Adrian Colyer
- @author Ramnivas Laddad
- @since 2.0
*/
"break encapsulation and do something AspectJ was not designed to do"——破坏封装,做 AspectJ 从没打算让⼈做的事。
怎么破的?静态块⾥,反射抠三个私有字段:
// [framework] .../RuntimeTestWalker.java:69-79
static {
try {
residualTestField = ShadowMatchImpl.class.getDeclaredField("residualTest");
varTypeField = ReflectionVar.class.getDeclaredField("varType");
myClassField = ReflectionBasedReferenceTypeDelegate.class.getDeclaredField("myClass");
}
catch (NoSuchFieldException ex) {
throw new IllegalStateException("The version of aspectjtools.jar / aspectjweaver.jar " +
"on the classpath is incompatible with this version of Spring: " + ex);
}
}residualTest 是 AspectJ 在静态匹配之后剩下的那棵待运⾏时求值的表达式树(residue,残式)。Spring 把它抠出来,⽤ ITestVisitor 遍历,⾃⼰判断"这残式⾥有没有this / target "。
判定⼿段本身也很有意思——⽤哨兵对象反推变量身份:
// [framework] .../RuntimeTestWalker.java:263-283
private final Object thisObj = new Object();
private final Object targetObj = new Object();
private final Object[] argsObjs = new Object[0];...@Override
public void visit(Instanceof i) {
ReflectionVar v = (ReflectionVar) i.getVar();
Object varUnderTest = v.getBindingAtJoinPoint(this.thisObj, this.targetObj, this.argsObjs);
if (varUnderTest == this.thisObj || varUnderTest == this.targetObj) {
this.testsSubtypeSensitiveVars = true;
}
}塞三个哨兵进去,看它把哪个吐回来——引⽤相等⼀⽐,就知道这个变量到底代表 this 还是 target 。相当巧。
⽽处理注解的那个分⽀,作者显然⾃⼰都撑不住了,留下了 Spring 源码⾥最出名的⼀句⾃嘲:
// [framework] .../RuntimeTestWalker.java:286-292@Override
public void visit(HasAnnotation hasAnn) {// If you thought things were bad before, now we sink to new levels of horror...
ReflectionVar v = (ReflectionVar) hasAnn.getVar();
int varType = getVarType(v);
if (varType == AT_THIS_VAR || varType == AT_TARGET_VAR || varType == AT_ANNOTATION_VAR) {
this.testsSubtypeSensitiveVars = true;
}
}"如果你觉得刚才已经够糟了,现在我们要下沉到新的恐怖层级。"
这些 AT_THIS_VAR 之类的常量,Spring ⾃⼰抄了⼀份数字表( [framework] .../RuntimeTestWalker.java:118-122 : THIS_VAR = 0 、 TARGET_VAR = 1 、
AT_THIS_VAR = 3 、 AT_TARGET_VAR = 4 、 AT_ANNOTATION_VAR = 8 ——2、5、6、7 缺席,Spring 只声明它关⼼的五个)。⚠ 本⼦系统最深的⼀处暗礁:那个 NoSuchFieldException 守卫只能挡住字段改名。如果 AspectJ 哪天调整了 varType 的编码含义——字段还叫 varType ,只是 3 不再
是 @this 了——Spring 会静默匹配错,没有任何守卫能发现。这才是"Spring 和 AspectJ 的版本必须严格配套"的真正原因:不是 API 不兼容,是私有实现细节的耦合。也正因如此, [framework] framework-platform/framework-platform.gradle:103-105 把 aspectjrt / aspectjtools / aspectjweaver 三件套死钉在同⼀个 1.9.25 。
(Bug 151593 ⾄今没修。这段"临时⽅案"从 @since 2.0 ⼀路活到了本基线 7.1——注意: @since 2.0 是源码⾥的标注,我未查 git 历史,但从标注推断,它⼤约已经活了快⼆⼗年。)
六、 isRuntime() :⼀个开关,两种代价// [framework] .../AspectJExpressionPointcut.java:340-343@Override
public boolean isRuntime() {
return obtainPointcutExpression().mayNeedDynamicTest();
}⼀⾏,完全委托给 AspectJ。表达式⾥含了 args(..) / this(..) / target(..) / @args(..) 这些必须看实际值的成分,它就返回 true 。
对⽐⼀下 Spring ⾃家那些实现,你就知道这个开关平时有多"硬": StaticMethodMatcher.isRuntime() 是 public final boolean 、恒返回 false ( [framework]spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcher.java:34 ); DynamicMethodMatcher 恒返回 true ,同样 final( .../DynamicMethodMatcher.java:32 )。两边都不许覆盖。 ⽽ AspectJExpressionPointcut 哪个都不继承——因为它必须按表达式逐个决定。
代价在哪:从"建链⼀次"变成"每次调⽤"
false 的世界很省:静态匹配⼀次定终身,链⼀建好就不再问了。
true 的世界不⼀样。建链时,每个拦截器都要被包⼀层:
// [framework] spring-aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java:84-96
if (match) {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
if (mm.isRuntime()) {
// Creating a new object instance in the getInterceptors() method// isn't a problem as we normally cache created chains.
for (MethodInterceptor interceptor : interceptors) {
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
}
else {
interceptorList.addAll(Arrays.asList(interceptors));
}
}
( InterceptorAndDynamicMethodMatcher 在本基线已经是个 record: record InterceptorAndDynamicMethodMatcher(MethodInterceptor interceptor,
MethodMatcher matcher) {} ,包级私有, [framework] .../InterceptorAndDynamicMethodMatcher.java:32 。本基线如此——早先版本它是个普通类。)然后每⼀次⽅法调⽤,链推进到这个位置时都要现算⼀遍:
// [framework] spring-aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java:163-175
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();
}
}注意"跳过"是递归调 proceed() ,不是 continue —— currentInterceptorIndex 已经⾃增过了,所以这是尾递归式前进。每⼀次动态不匹配,都在栈上多压⼀层。(本来AOP 的栈就够深了。)
MethodMatcher 的 javadoc 把这个时机点得⾮常准,⽽且有⼀句极容易被忽略:
"…the 3-arg method will be invoked immediately before each potential execution of the related advice … All previous advice, such as earlier interceptors in aninterceptor chain, will have run, so any state changes they have produced in parameters or ThreadLocal state will be available at the time of evaluation." ——[framework] spring-aop/src/main/java/org/springframework/aop/MethodMatcher.java:37-44


动态匹配发⽣在拦截器链推进的途中,不是链构建的时候。 也就是说,排在你前⾯的通知已经跑完了,它们改过的参数、写过的 ThreadLocal,你这⾥全看得⻅。这既是特性(你可以据此决策),也是坑(切点的匹配结果依赖于前⾯通知的副作⽤,顺序⼀变⾏为就变)。
运⾏时那⼀趟到底⼲了什么// [framework] .../AspectJExpressionPointcut.java:345-402(节选)
MethodInvocation curr = ExposeInvocationInterceptor.currentInvocation();
if (curr.getMethod() == method) {
targetObject = curr.getThis();...
pmi = currPmi;
thisObject = pmi.getProxy();
}...
JoinPointMatch joinPointMatch = shadowMatch.matchesJoinPoint(thisObject, targetObject, args);thisObject 取的是 pmi.getProxy() ——壳; targetObject 取的是 curr.getThis() ——原件。前⾯第三节讲的那条绑定约定,就是在这⾥落地的。
这段代码依赖 ExposeInvocationInterceptor 提前把当前调⽤塞进了⼀个 NamedThreadLocal ( [framework] spring-aop/src/main/java/org/springframework/aop/interceptor/ExposeInvocationInterceptor.java:61-62 )。谁负责插它?
// [framework] spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJProxyUtils.java:61-64
if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {
advisors.add(0, ExposeInvocationInterceptor.ADVISOR);
return true;
}
add(0, ...) ——插在链⾸。判定"有没有 AspectJ advice"的三个条件⾥,第三个正是 pointcutAdvisor.getPointcut() instanceof AspectJExpressionPointcut
( :73-77 )。⽽它的 getOrder() 是 PriorityOrdered.HIGHEST_PRECEDENCE + 1 ( ExposeInvocationInterceptor.java:104-106 )——注意那个 + 1 ,它给"⽐我更⾼优先级"留了⼀格空位,⽽这⼀格正是那条异常消息⾥警告你的:
"note that advices with order HIGHEST_PRECEDENCE will execute before ExposeInvocationInterceptor!" —— [framework].../ExposeInvocationInterceptor.java:77
⚠ 你要是把某个⾃定义 advice 的 order 设成 HIGHEST_PRECEDENCE ,它就跑在 ThreadLocal 被填之前,此时任何依赖 currentInvocation() 的东⻄都会炸。
最后⼀段是参数绑定—— args(id) ⾥那个 id 怎么送进你的通知⽅法形参的:
// [framework] .../AspectJExpressionPointcut.java:432-440
private void bindParameters(ProxyMethodInvocation invocation, JoinPointMatch jpm) {
// Note: Can't use JoinPointMatch.getClass().getName() as the key, since// Spring AOP does all the matching at a join point, and then all the invocations// under this scenario, if we just use JoinPointMatch as the key, then// 'last man wins' which is not what we want at all.// Using the expression is guaranteed to be safe, since 2 identical expressions// are guaranteed to bind in exactly the same way.
invocation.setUserAttribute(resolveExpression(), jpm);
}✨ key ⽤的是表达式字符串本身。 为什么不⽤类名?因为同⼀个连接点上会有多个通知依次执⾏,⽤ JoinPointMatch 的类名当 key 就是"last man wins"——最后⼀个把前⾯
的覆盖掉。⽤表达式当 key 则天然安全,理由写在注释⾥:两个完全相同的表达式,必然以完全相同的⽅式绑定参数。
读取端在通知那⼀侧,⽤的是⼀模⼀样的 key 约定:
// [framework] spring-aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java:684-686
protected @Nullable JoinPointMatch getJoinPointMatch(ProxyMethodInvocation pmi) {
String expression = this.pointcut.getExpression();
return (expression != null ? (JoinPointMatch) pmi.getUserAttribute(expression) : null);
}
⚠ 暗礁:整个运⾏时匹配包在 try { ... } catch (Throwable ex) { ...; return false; } ⾥( :395-401 ),⽇志级别⼜是 DEBUG,注释写着 "falling back to non-match"。运⾏时匹配⼀旦出任何岔⼦,结果就是"这条通知悄悄不执⾏"。 跟第四节那个静默失效是同⼀种病:宁可少做,也不让你知道。
反过来:有⼈会主动要求"请把我变成动态的"
isRuntime() 通常是被表达式推成 true 的。但有⼀处,Spring 是主动把⼀个本可以静态判定的切点包成动态的——⾮单例切⾯。
// [framework] spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java:97-114
if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {// Static part of the pointcut is a lazy type.
Pointcut preInstantiationPointcut = Pointcuts.union(
aspectInstanceFactory.getAspectMetadata().getPerClausePointcut(), this.declaredPointcut);// Make it dynamic: must mutate from pre-instantiation to post-instantiation state.// If it's not a dynamic pointcut, it may be optimized out// by the Spring AOP infrastructure after the first evaluation.
this.pointcut = new PerTargetInstantiationModelPointcut(
this.declaredPointcut, preInstantiationPointcut, aspectInstanceFactory);
this.lazy = true;
}
else {// A singleton aspect.
this.pointcut = this.declaredPointcut; //就是那个 AspectJExpressionPointcut本尊
this.lazy = false;
this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);
}看那⾏注释的措辞——"Make it dynamic"。⽤ perthis / pertarget 声明的切⾯,切⾯实例是每个⽬标对象⼀份、按需创建的,于是"切⾯实例化之前"和"之后"这两个阶段,
切点的语义并不相同。⽽ PerTargetInstantiationModelPointcut extends DynamicMethodMatcherPointcut ( :263 )——继承⾃那个 isRuntime() 恒为 true 且final 不可覆盖的基类。
为什么⾮动态不可?类头注释说得直⽩( :260-261 ):
"Note that this is adynamic pointcut; otherwise it might be optimized out if it does not at first match statically."因为静态匹配的整套缓存机制建⽴在⼀个前提上:结果不随时间改变。 ⼀旦这个前提不成⽴(第⼀次问的时候切⾯还没实例化、答"不匹配",之后应该变成"匹配"),缓存就成了错误的固化。唯⼀的出路是宣布⾃⼰动态,放弃全部缓存收益,每次调⽤现算。
这是⼀次代价明确的⾃我降级:你写下 @Aspect("perthis(...)") 这⼀⾏的同时,也就替这个切⾯上的每⼀次⽅法调⽤都买了单。绝⼤多数⼈⽤不到 perthis ,但⽤到的⼈应该知道账单在哪。
七、 AopUtils.canApply :最终裁决所前⾯所有零件,最后都汇到这⼀个静态⽅法上。启动期每⼀个 (advisor × bean) 组合都要过它。
// [framework] spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java:239-274
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
Assert.notNull(pc, "Pointcut must not be null");
if (!pc.getClassFilter().matches(targetClass)) {
return false; //①
}
MethodMatcher methodMatcher = pc.getMethodMatcher();
if (methodMatcher == MethodMatcher.TRUE) {// No need to iterate the methods if we're matching any method anyway...
return true; //②
}
IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher iamm) {
introductionAwareMethodMatcher = iamm;
}
Set<Class<?>> classes = new LinkedHashSet<>();
if (!Proxy.isProxyClass(targetClass)) {
classes.add(ClassUtils.getUserClass(targetClass)); //③
}
classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
for (Class<?> clazz : classes) {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
for (Method method : methods) {
if (introductionAwareMethodMatcher != null ?
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
methodMatcher.matches(method, targetClass)) {
return true; //④
}
}
}
return false;
}逐条读出意图:
① 类级短路,是整个 AOP 启动性能的命⻔。 ⼀个中型 Boot 应⽤,⼏百上千件器 × ⼗⼏个 advisor,如果每次都要遍历⽅法,启动会⾁眼可⻅地慢。 ClassFilter 存在的全部理由,就是让这个 return false 尽早发⽣。
② ⽤的是 == ,引⽤相等,不是 equals ——因为 MethodMatcher.TRUE 是单例 TrueMethodMatcher.INSTANCE ( [framework].../MethodMatcher.java:105 )。恒真就整段跳过。
③ ClassUtils.getUserClass(targetClass) 会剥掉 CGLIB 的 $$ ⽣成类,取回它的⽗类——匹配永远针对"你写的那个类",不是⽣成类。⽽如果⽬标本身就是个JDK 代理,则不把它⾃⼰加进来,只看接⼝:代理类的⽅法是合成的、没有注解、名字也不承载业务语义,扔进匹配集只会制造误判。
④ ⼀个⽅法命中就返回。 因为 canApply 回答的问题是"这个 advisor 值不值得为这个类建壳",⽽不是"哪些⽅法要被刻上⼯序"。后者留给建链时的DefaultAdvisorChainFactory 逐⽅法再算。两级判定、两种粒度——这也是为什么同⼀个切点会被问两遍,很多⼈第⼀次看堆栈时会疑惑"怎么⼜匹配了⼀次"。
⚠ 那个坑: Object 的⽅法也算数
getAllDeclaredMethods 传的 mf 是 null :
// [framework] spring-core/src/main/java/org/springframework/util/ReflectionUtils.java:389-393
public static Method[] getAllDeclaredMethods(Class<?> leafClass) {
final List<Method> methods = new ArrayList<>(20);
doWithMethods(leafClass, methods::add);
return methods.toArray(EMPTY_METHOD_ARRAY);
}
⽽ doWithMethods ⾥两道"到 Object 就停"的守卫,条件都是 mf == USER_DECLARED_METHODS :// [framework] .../ReflectionUtils.java:356-359, 373-375
if (mf == USER_DECLARED_METHODS && clazz == Object.class) {// nothing to introspect
return;
}...
if (clazz.getSuperclass() != null && (mf != USER_DECLARED_METHODS || clazz.getSuperclass() != Object.class)) {
doWithMethods(clazz.getSuperclass(), mc, mf);
}mf 是 null ,两道守卫都不⽣效。所以遍历会⼀路⾛到 Object ,把 toString / equals / hashCode / wait / notify / getClass 全部纳⼊匹配集。
后果:你写⼀个 execution(* *(..)) 这种宽切点,哪怕⽬标类⾃⼰⼀个⽅法都没有,也会因为 Object.toString() 命中⽽返回 true ——壳照建不误。这就是"为什么我加了个宽切⾯,整个应⽤到处都是代理"的机械原因。
两趟扫描,顺序敏感// [framework] .../AopUtils.java:319-340
List<Advisor> eligibleAdvisors = new ArrayList<>();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
}
}
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor) {
continue; // already processed
}
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
}必须两趟,因为 hasIntroductions 是第⼆趟的输⼊(第五节说过:有 introduction 时 maybe ⼀律放⾏)。副产品是:introduction advisor 天然排在链的前⾯。
顺带⼀提, canApply(Advisor, ...) 那层的三分⽀也很能说明各⾃的定位:
// [framework] .../AopUtils.java:298-309
if (advisor instanceof IntroductionAdvisor ia) {
return ia.getClassFilter().matches(targetClass); //只过 ClassFilter
}
else if (advisor instanceof PointcutAdvisor pca) {
return canApply(pca.getPointcut(), targetClass, hasIntroductions);
}
else {// It doesn't have a pointcut so we assume it applies.
return true;
}IntroductionAdvisor 只过类级,不过⽅法级——因为它⼲的事是"给这个类加个接⼝",跟哪个⽅法没关系。⽽最后那个 return true 也很坦⽩:没切点就假定适⽤。
⼋、 bean() :只借表达式,反倒换来了⾃由
前⾯说了, bean() 不在 SUPPORTED_PRIMITIVES ⾥。它⾛的是 AspectJ 提供的扩展⼝: parser.registerPointcutDesignatorHandler(new
BeanPointcutDesignatorHandler()) ( :246 )。这件事的分量在于—— bean() 是⼀个 AspectJ 语法能表达、但 AspectJ 语义根本⽆法实现的指示符。⽂档说得很直⽩:
"The bean PCD is supported only in Spring AOP and not in native AspectJ weaving. It is a Spring-specific extension…" —— [framework].../pointcuts.adoc:131-133道理很简单:AspectJ 织⼊发⽣在编译期或类加载期,那时候"Spring bean 名字"这个概念还不存在。只有 Spring 这种"在运⾏时按名字建壳"的模型,才谈得上按 bean 名切。
所以"只借表达式"不是⼀道限制,它反⽽换来了扩展⾃由:既然匹配逻辑完全在⾃⼰⼿⾥,就可以往⾥塞 AspectJ 做梦都实现不了的语义。
它的燃料来⾃⼀条挂在线程上的绳:
// [framework] spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java:130-140
protected List<Advisor> findAdvisorsThatCanApply(
List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
}
finally {
ProxyCreationContext.setCurrentProxiedBeanName(null);
}
}只在这个 try 块的窗⼝⾥有值。 窗⼝⼀关, bean() 就再也不知道⾃⼰在给谁匹配了。那它该返回什么?
// [framework] .../AspectJExpressionPointcut.java:657-665
private FuzzyBoolean contextMatch(@Nullable Class<?> targetType) {
String advisedBeanName = getCurrentProxiedBeanName();
if (advisedBeanName == null) { // no proxy creation in progress
// abstain; can't return YES, since that will make pointcut with negation fail
return FuzzyBoolean.MAYBE;
}
if (BeanFactoryUtils.isGeneratedBeanName(advisedBeanName)) {
return FuzzyBoolean.NO;
}...
}✨ 返回 MAYBE——弃权,⽽不是拒绝。 这⼀笔很漂亮。类头注释解释了原因:
"For static match tests, this matcher abstains to allow the overall pointcut to match even when negation is used with the bean() pointcut." —— [framework].../AspectJExpressionPointcut.java:616-618
想⼀下:如果窗⼝外返回 NO ,那 !bean(foo) 就变成了恒真——所有东⻄全被通知⼀遍。⽤弃权来保护否定语义,这是三态逻辑真正发挥威⼒的地⽅(⼆值逻辑在这⾥必然出错)。
同⼀段还有两个细节值得记:⾃动⽣成的 bean 名( #0 这类匿名内部定义)直接判 NO ,因为按名匹配对没有稳定名字的东⻄毫⽆意义;⽬标是 FactoryBean 实现类时会⽤&name 去试,类型未知时两种都试。
⚠ 最后⼀个少有⼈知的暗礁: bean() 的实际匹配⾛的是——
// [framework] .../AspectJExpressionPointcut.java:677-680
private boolean matchesBean(String advisedBeanName) {
return BeanFactoryAnnotationUtils.isQualifierMatch(
this.expressionPattern::matches, advisedBeanName, beanFactory);
}isQualifierMatch ——它不只匹配 bean 名,还会顺带匹配 @Qualifier 的值和别名。你写 bean(orderService) ,可能会匹配到⼀个叫别的名字、但
@Qualifier("orderService") 的器。⽽底层的模式对象是 AspectJ 的 org.aspectj.weaver.patterns.NamePattern ( :622 )——⼜⼀次"只借零件,不⽤引擎"。🦴 ⻣灰级细节
⼀、 ShadowMatch 有⼀份全局缓存,⽽它在单例造完那⼀刻被清空。
// [framework] spring-aop/src/main/java/org/springframework/aop/aspectj/ShadowMatchUtils.java:32-58(@since 6.2)
public abstract class ShadowMatchUtils {
private static final Map<Object, ShadowMatch> shadowMatchCache = new ConcurrentHashMap<>(256);
static @Nullable ShadowMatch getShadowMatch(Object key) { return shadowMatchCache.get(key); }
static ShadowMatch setShadowMatch(Object key, ShadowMatch shadowMatch) {
ShadowMatch existing = shadowMatchCache.putIfAbsent(key, shadowMatch);
return (existing != null ? existing : shadowMatch);
}...
}
缓存键是个 record: private record ShadowMatchKey(AspectJExpressionPointcut expression, Method method) {} ( AspectJExpressionPointcut.java:728 )。record 的 equals ⾛成员的 equals ,⽽ AspectJExpressionPointcut.equals() ⽐的是表达式 + 声明作⽤域 + 参数名 + 参数类型( :552-559 ),不是对象身份。于是——表达式字符串相同的多个切点对象,共享同⼀条缓存。对"⼀个 @Pointcut 被⼗个通知引⽤"这种常⻅写法,收益极⼤。
清理时机是全书⾥我最喜欢的⼀处取舍:
// [framework] spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java:114-122@Override
public void afterSingletonsInstantiated() {
ShadowMatchUtils.clearCache();
}@Override
public void destroy() {
ShadowMatchUtils.clearCache();
}所有单例造完,⽴刻清空。 因为启动期的匹配洪峰已经过去,⽽这些 ShadowMatch 背后挂着 AspectJ 的类型图,常驻内存不便宜。代价是:懒加载的器、原型器、运⾏时新建的壳,都得重算⼀遍。⼀次明确的"内存换驻留"取舍。
⚠ 但这两个钩⼦只挂在 AspectJAwareAdvisorAutoProxyCreator 这⼀⽀上。如果你是⽤ ProxyFactory / AspectJProxyFactory ⼿⼯建壳,清理永远不会被触发——那
个 static Map 会⼀直攥着 Class 和 Method 的强引⽤。
⼆、那把锁锁的不是 this 。
// [framework] .../AspectJExpressionPointcut.java:469-470
PointcutExpression pointcutExpression = obtainPointcutExpression();
synchronized (pointcutExpression) {锁的是 AspectJ 的 PointcutExpression 对象本身。原因:AspectJ 的 ReflectionWorld 内部不是线程安全的,同⼀个表达式并发调 matchesMethodExecution 会出事。锁在这个对象上,粒度精确到"每个表达式⼀把锁",不同切点之间互不阻塞。
有意思的是隔壁 obtainPointcutExpression() 却是⽆锁的 check-then-act( :195-204 )——两个线程可能各 build ⼀份,最后写⼊的胜出。这是有意的:构建幂等,重复⼀次只浪费点 CPU,⽐加锁划算。同⼀个类⾥,⼀处敢不加锁、⼀处必须加锁,判断依据是"背后那个第三⽅对象线程安全吗"。
三、 toString() 是语义契约,不是调试辅助。
ClassFilter 和 MethodMatcher 两个接⼝的 javadoc 带着同⼀条 WARNING:
"Concrete implementations of this interface must provide proper implementations of equals() , hashCode() , and toString() … 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] .../ClassFilter.java:26-33 、 [framework] .../MethodMatcher.java:46-53
为什么 toString() 会升格成契约?javadoc 点了名:"in order to allow the matcher to be used in caching scenarios — for example, in proxies generated by CGLIB"。两个 equals 为 true 但 toString 不同的 matcher,会让本可复⽤的代理类被重复⽣成——类膨胀、Metaspace 压⼒。 @since 精确到 6.0.13,说明这是⼀次带修复性质的收紧,本基线(7.1)沿⽤。
⾃⼰写 MethodMatcher 的⼈,⼗个有九个漏了这条。
四、为了骗过 AspectJ,Spring 会凭空造⼀个接⼝。
// [framework] .../AspectJExpressionPointcut.java:442-462
private ShadowMatch getTargetShadowMatch(Method method, Class<?> targetClass) {
Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
if (targetMethod.getDeclaringClass().isInterface() && targetMethod.getDeclaringClass() != targetClass &&
obtainPointcutExpression().getPointcutExpression().contains("." + targetMethod.getName() + "(")) {
// Note: AspectJ is only going to take Method.getDeclaringClass() into account.
Set<Class<?>> ifcs = ClassUtils.getAllInterfacesForClassAsSet(targetClass);
if (ifcs.size() > 1) {
try {
Class<?> compositeInterface = ClassUtils.createCompositeInterface(
ClassUtils.toClassArray(ifcs), targetClass.getClassLoader());
targetMethod = ClassUtils.getMostSpecificMethod(targetMethod, compositeInterface);
}
catch (IllegalArgumentException ex) {// Implemented interfaces probably expose conflicting method signatures...
}
}
}
return getShadowMatch(targetMethod, method);
}问题背景在那⾏注释⾥:AspectJ 判 execution(* com.Foo.bar()) 时只看 Method.getDeclaringClass() 。当⽬标是 JDK 代理、⽅法来⾃接⼝ A、⽽你的表达式写的是接⼝ B ⾥的同名⽅法时,就会漏匹配。
解法是造⼀个继承了⽬标类所有接⼝的合成接⼝,把⽅法重定位到它上⾯,让 AspectJ 看到"最全"的声明类型。
⽽触发条件苛刻得像⼿术⼑,三个 && :声明类是接⼝、且不等于⽬标类、且表达式字符串⾥字⾯含有 .⽅法名( 。第三个是纯字符串启发式——只有表达式明确点了这个⽅法的名,才值得付造类的代价。这是"⽤⼀个廉价的脏检查,守住⼀个昂贵的正确性修复"的典型。
(同类的字符串嗅探还有⼀处: containsAnnotationPointcut() 就是 resolveExpression().contains("@annotation") , :537-539 。它服务于另⼀条退路——JDK 代理⽣成的类,其重声明的⽅法上没有任何注解(注释原话:"a negative match on a proxy class, which doesn't carry any annotations on its redeclared methods", :497-499 ),所以含 @annotation 的表达式必须退回原始 Method 重匹配。同⼀条物理事实在⾮ AspectJ 那条路上也被独⽴处理过⼀次: [framework] spring-aop/src/main/java/org/springframework/aop/support/annotation/AnnotationMethodMatcher.java:77-79 —— // Proxy classes never have annotations ontheir redeclared methods. )
五、 union 修了⼀个分配律错误。
// [framework] spring-aop/src/main/java/org/springframework/aop/support/MethodMatchers.java:135-138@Override
public boolean matches(Method method, Class<?> targetClass) {
return (matchesClass1(targetClass) && this.mm1.matches(method, targetClass)) ||
(matchesClass2(targetClass) && this.mm2.matches(method, targetClass));
}Pointcuts.union(pc1, pc2) 的正确语义是 (cf1∧mm1) ∨ (cf2∧mm2) ,不是 (cf1∨cf2) ∧ (mm1∨mm2) ——后者会把"pc1 的类 + pc2 的⽅法"这种交叉组合错误地放⾏。
Spring 的解法是把 ClassFilter 下沉进 MethodMatcher( ClassFilterAwareUnionMethodMatcher , :202-222 ,覆写 matchesClass1/2 委托给各⾃的过滤器)。
⽽ isRuntime() 的合并规则是 mm1.isRuntime() || mm2.isRuntime() ( :149-151 )——⼀边要动态,整体就动态。安全侧优先:宁可多做⼀次运⾏时检查。
六、Spring ⾃⼰最重要的那个切⾯,压根不⾛这条路。
读到这⾥很容易⽣出⼀个印象:Spring AOP 的切点匹配 = AspectJ 表达式匹配。不是的。
@Transactional 是全 Spring ⽣态⽤得最多的切⾯。它的切点⻓这样:
// [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAttributeSourcePointcut.java:39, 45
final class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
public TransactionAttributeSourcePointcut() {
setClassFilter(new TransactionAttributeSourceClassFilter());
}...
}⼀个 AspectJ 的字都没有。 StaticMethodMatcherPointcut extends StaticMethodMatcher implements Pointcut ( [framework] spring-
aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcut.java:33 ),⽽ StaticMethodMatcher.isRuntime() 是 public final 、恒false ( .../StaticMethodMatcher.java:34 )——永远静态,永不动态复核。ClassFilter 也是⾃⼰⼿写的⼀个内部类( :80 )。
同⼀套路还有两处: @Cacheable 的 CacheOperationSourcePointcut 同样 extends StaticMethodMatcherPointcut ( [framework] spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperationSourcePointcut.java:39 ); @Async 则是拿 AnnotationMatchingPointcut 拼出来的( [framework] spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java:172-178 ,ComposablePointcut 组合类级与⽅法级两个匹配器)。
这件事值得单独拎出来说,因为它纠正了⼀个很常⻅的误解: aspectjweaver 不在类路径上, @Transactional 、 @Cacheable 、 @Async 照样⼯作——它们⽤的是 Spring⼿写的 Pointcut 实现,⽽不是表达式。回头看 Boot 那段⾃动配置就明⽩了:类路径上没有 org.aspectj.weaver.Advice 时,⾛的是 ClassProxyingConfiguration ,只注册⼀个⾃动代理创建器( [boot] .../AopAutoConfiguration.java:70-83 )——壳照套,只是没⼈会给你解析 execution(...) 了。
所以本章讲的这套 AspectJ 表达式匹配,准确说是"当你⾃⼰写 @Aspect 时才会⽤到的那条路"。框架内置的那些切⾯⾛的是更短、更快、更可控的另⼀条。
⚠ 暗礁总表
暗礁 后果
1不⽀持的 PCD 静默失效:⽂档承诺抛 IllegalArgumentException ,实际被吞成 DEBUG ⽇志 +永久熔断切⾯完全不⽣效,不开 DEBUG 毫⽆线索( AspectJExpressionPointcut.java:296-301 )
暗礁 后果
2RuntimeTestWalker 反射 AspectJ 三个私有字段;字段改名会启动即炸,字段语义改了则静默匹配错,⽆任何守卫Spring 与 AspectJ 版本必须严格配套( RuntimeTestWalker.java:69-79 )
3 and / or / not 是纯字符串替换 名字⾥含 " and " 会被误伤( :257-262 )
4 canApply 会遍历到 Object 的⽅法宽切点⼏乎必然命中 → 到处⽣壳( AopUtils.java:263 + ReflectionUtils.java:373-375 )
5 运⾏时匹配⼀律 catch (Throwable) → return false 通知悄⽆声息地不执⾏( :395-401 )
6 bean() 只在建壳窗⼝内有值,窗⼝外⼀律 MAYBE⼿⼯ ProxyFactory 建壳时语义漂移( AbstractAdvisorAutoProxyCreator.java:133-139 )
7 bean() 会顺带匹配 @Qualifier 值与别名 匹配到你没预期的器( :677-680 )
8 ShadowMatch 全局缓存的清理只挂在 AspectJAwareAdvisorAutoProxyCreator 上 ⼿⼯建壳路径不会触发清理( ShadowMatchUtils.java:34 )
9 ⾃定义 MethodMatcher 漏写 toString() CGLIB 代理类⽆法复⽤,Metaspace 压⼒(6.0.13 起的契约)
10 ⾃调⽤不被拦截⽂档原话:"calls within the target object are, by definition, notintercepted"( pointcuts.adoc:97-98 )
第 10 条不是这套匹配机制的锅——它是代理模型的地基。你的切点写得再准,只要那次调⽤没经过壳,判定根本不会被触发。 这就是全书那句"⾃⼰⼈在壳⾥⾯喊⾃⼰⼈,喊声传不到壳上"。切点管的是"刻在哪些位置",但壳罩不到的地⽅,刻了也⽩刻。
🎯 三句带⾛1. Spring 只⽤ AspectJ 的三个⽅法: couldMatchJoinPointsInType (类级)、 matchesMethodExecution (⽅法级)、 ShadowMatch.matchesJoinPoint (运⾏时)。
解析和判定借 AspectJ,建代理、串链、跑通知全是 Spring ⾃⼰的; aspectjweaver 在 spring-aop.gradle ⾥是 optional ——⽽且框架内置的@Transactional / @Cacheable / @Async ⾛的是⼿写 Pointcut ,连表达式都不⽤。
2. 匹配是两级 + 三态: ClassFilter.matches(Class) 先短路,命中才逐⽅法跑 MethodMatcher ; ShadowMatch 返回 always / never / maybe,maybe 时若
isRuntime() 为真,则每次⽅法调⽤都要在 ReflectiveMethodInvocation.proceed() ⾥现算⼀遍。含 args / this / target / @args 的切点就⾛这条贵路。- AopUtils.canApply 只回答"值不值得建代理",⼀个⽅法命中即返回 true,且遍历包含 Object 的⽅法——所以 execution(* *(..)) 这类宽切点会让代理遍地开花。"哪些⽅法真要被通知"是建链时 DefaultAdvisorChainFactory 另算的第⼆级判定。
承上启下到这⾥,"刻在哪些位置"这件事已经⽔落⽯出:⼀⾏字符串,经 AspectJ 的解析器变成语法树,再由 Spring 分两级、按三态问出⼀个 true 或 false 。
但请注意,我们从头到尾只是在判断。 AopUtils.canApply 返回 true 之后呢?谁拿着这个 true 去动⼿?那个把你⾟⾟苦苦造好的器换成另⼀个对象的动作,究竟发⽣在哪⼀刻、由谁执⾏、⼜是怎么做到"你在图纸上写的是 A,坊⾥递到你⼿上的是套了壳的 A"⽽你毫⽆察觉?
答案是⼀个 BeanPostProcessor ——过⼿的⼈可以掉包。下⼀章 AbstractAutoProxyCreator :壳是怎么装上的。我们会看到它在 postProcessAfterInitialization 这个不起眼的钩⼦⾥,⽤⼀⾏ return proxy 完成了整个 Spring AOP 最关键、也最容易被误解的⼀次调包。