SpringAOP 源码之创建代理对象及执行

ProxyFactory

ProxyFactory#getProxy

定位: org.springframework.aop.framework.ProxyFactory#getProxy

1
2
3
4
public Object getProxy(@Nullable ClassLoader classLoader) {  
// createAopProxy() 用来创建我们的代理工厂
return createAopProxy().getProxy(classLoader);
}

createAopProxy

定位: org.springframework.aop.framework.ProxyCreatorSupport#createAopProxy

创建 AOP 代理,如果激活了,就需要有激活通知

1
2
3
4
5
6
7
8
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
// 监听调用 AdvisedSupportListener 实现类的 activated 方法
activate();
}
// 通过 AopProxyFactory 获得 AopProxy ,这个 AopProxyFactory 是在初始化函数中定义的,使用的是 DefaultAopProxyFactory
return getAopProxyFactory().createAopProxy(this);
}

定位: org.springframework.aop.framework.DefaultAopProxyFactory#createAopProxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
// 这段代码用来判断选择哪种创建代理对象的方式
// config.isOptimize() 是否对代理类的生成使用策略优化 其作用是和 isProxyTargetClass 是一样的 默认为 false
// config.isProxyTargetClass() 是否使用 Cglib 的方式创建代理对象 默认为 false
// hasNoUserSuppliedProxyInterfaces 目标类是否有接口存在 且只有一个接口的时候接口类型不是SpringProxy 类型
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
// 上面的三个方法有一个为true的话,则进入到这里
// 从AdvisedSupport中获取目标类 类对象
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
// 判断目标类是否是接口 如果目标类是接口的话,则还是使用JDK的方式生成代理对象
// 如果目标类是 Proxy 类型 则还是使用 JDK 的方式生成代理对象
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
// 配置了使用 Cglib 进行动态代理或者目标类没有接口,那么使用 Cglib 的方式创建代理对象
return new ObjenesisCglibAopProxy(config);
}
else {
// 使用 JDK 的提供的代理方式生成代理对象
return new JdkDynamicAopProxy(config);
}
}

JdkDynamicAopProxy

JdkDynamicAopProxy#getProxy

定位: org.springframework.aop.framework.JdkDynamicAopProxy#getProxy

创建代理对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
// 获取 AdvisedSupport 类型对象的所有接口
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
// 接口是否定义了 equals 和 hashcode 方法 (正常是没有的)
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
// 创建代理对象 this 是 JdkDynamicAopProxy
// JdkDynamicAopProxy 同时实现了 InvocationHandler 接口
// 这里我们生成的代理对象可以向上造型为任意 proxiedInterfaces 中的类型
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

定位: org.springframework.aop.framework.AopProxyUtils#completeProxiedInterfaces

获取目标类上的接口并且判断是否需要添加 SpringProxy Advised DecoratingProxy 接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
static Class<?>[] completeProxiedInterfaces(AdvisedSupport advised, boolean decoratingProxy) {
// 获取AdvisedSupport类型中目标类的接口
Class<?>[] specifiedInterfaces = advised.getProxiedInterfaces();
// 如果目标类没有实现接口的话
if (specifiedInterfaces.length == 0) {
// No user-specified interfaces: check whether target class is an interface.
// 获取目标类
Class<?> targetClass = advised.getTargetClass();
if (targetClass != null) {
// 如果目标类是接口,则把目标类添加到AdvisedSupport的接口集合中
if (targetClass.isInterface()) {
advised.setInterfaces(targetClass);
}
// 如果是Proxy类型
else if (Proxy.isProxyClass(targetClass)) {
advised.setInterfaces(targetClass.getInterfaces());
}
// 重新获取接口
specifiedInterfaces = advised.getProxiedInterfaces();
}
}
//接口中有没有 SpringProxy 类型的接口
//是否需要添加 SpringProxy 接口
boolean addSpringProxy = !advised.isInterfaceProxied(SpringProxy.class);
// isOpaque 代表生成的代理是否避免转化为 Advised 类型 默认为 false 如果目标类没有实现 Advised 接口
// 是否需要添加 Advised 接口
boolean addAdvised = !advised.isOpaque() && !advised.isInterfaceProxied(Advised.class);
// 是否需要添加 DecoratingProxy 接口
boolean addDecoratingProxy = (decoratingProxy && !advised.isInterfaceProxied(DecoratingProxy.class));
int nonUserIfcCount = 0;
// 需要添加 SpringProxy 接口
if (addSpringProxy) {
nonUserIfcCount++;
}
// 需要添加通知
if (addAdvised) {
nonUserIfcCount++;
}
// 需要添加 DecoratingProxy 接口
if (addDecoratingProxy) {
nonUserIfcCount++;
}
Class<?>[] proxiedInterfaces = new Class<?>[specifiedInterfaces.length + nonUserIfcCount];
// 扩展接口数组
System.arraycopy(specifiedInterfaces, 0, proxiedInterfaces, 0, specifiedInterfaces.length);
int index = specifiedInterfaces.length;
if (addSpringProxy) {
// 为目标对象接口中添加 SpringProxy 接口
proxiedInterfaces[index] = SpringProxy.class;
index++;
}
if (addAdvised) {
// 为目标对象接口中添加 Advised 接口
proxiedInterfaces[index] = Advised.class;
index++;
}
if (addDecoratingProxy) {
// 为目标对象接口中添加 DecoratingProxy 接口
proxiedInterfaces[index] = DecoratingProxy.class;
}
return proxiedInterfaces;
}

JdkDynamicAopProxy#invoke (执行入口)

定位: org.springframework.aop.framework.JdkDynamicAopProxy#invoke

被拦截的接口方法的入口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;

// 获取到我们的目标对象
TargetSource targetSource = this.advised.targetSource;
Object target = null;

try {
// 若是 equals 方法不需要代理
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
// 若是 hashCode 方法不需要代理
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
// 若是 DecoratingProxy 也不要拦截器执行
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
// isAssignableFrom 方法:如果调用这个方法的 class 或接口与参数 cls 表示的类或接口相同,或者是参数 cls 表示的类或接口的父类,则返回 true
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}

Object retVal;

/**
* 这个配置是暴露我们的代理对象到线程变量中,需要搭配@EnableAspectJAutoProxy(exposeProxy = true)一起使用
* 比如在目标对象方法中再次获取代理对象可以使用这个AopContext.currentProxy()
* 还有的就是事务方法调用事务方法的时候也是用到这个
*/
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
// 把我们的代理对象暴露到线程变量中
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}

// Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
// 获取我们的目标对象
target = targetSource.getTarget();
// 获取我们目标对象的 class
Class<?> targetClass = (target != null ? target.getClass() : null);

// Get the interception chain for this method.
// 从 Advised 中根据方法名和目标类获取AOP拦截器执行链
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

// Check whether we have any advice. If we don't, we can fallback on direct
// reflective invocation of the target, and avoid creating a MethodInvocation.
// 如果拦截器链为空
if (chain.isEmpty()) {
// We can skip creating a MethodInvocation: just invoke the target directly
// Note that the final invoker must be an InvokerInterceptor so we know it does
// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
// 通过反射直接调用执行
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
// 如果没有发现任何拦截器那么直接调用切点方法
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// We need to create a method invocation...
// 将拦截器封装在 ReflectiveMethodInvocation,以便于使用其 proceed 进行处理
MethodInvocation invocation =
new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
// 执行拦截器链
retVal = invocation.proceed();
}

// Massage return value if necessary.
// 获取返回类型
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
}
// 返回值类型错误
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}
finally {
// 如果目标对象不为空且目标对象是可变的,如prototype类型
// 通常我们的目标对象都是单例的,即targetSource.isStatic为true
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
// 释放目标对象
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
// 线程上下文复位
AopContext.setCurrentProxy(oldProxy);
}
}
}

ObjenesisCglibAopProxy

CglibAopProxy#getProxy

定位:org.springframework.aop.framework.CglibAopProxy#getProxy

创建代理对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
}

try {
// 从advised中获取ioc容器中配置的target对象
Class<?> rootClass = this.advised.getTargetClass();
Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

Class<?> proxySuperClass = rootClass;
//如果目标对象已经是CGLIB 生成代理对象(就是比较类名称中有 $$ 字符串),那么就取目标对象的父类作为目标对象的类
if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
proxySuperClass = rootClass.getSuperclass();
// 获取原始父类的接口
Class<?>[] additionalInterfaces = rootClass.getInterfaces();
for (Class<?> additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}

// Validate the class, writing log messages as necessary.
// 打印出不能代理的方法名,CGLIB 是使用继承实现的,所以final , static 的方法不能被增强
validateClassIfNecessary(proxySuperClass, classLoader);

// Configure CGLIB Enhancer...
// 创建及配置Enhancer
Enhancer enhancer = createEnhancer();
if (classLoader != null) {
enhancer.setClassLoader(classLoader);
if (classLoader instanceof SmartClassLoader &&
((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
enhancer.setUseCache(false);
}
}
// 配置超类,代理类实现的接口,回调方法等
enhancer.setSuperclass(proxySuperClass);
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));

// 获取callbacks
Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
// fixedInterceptorMap only populated at this point, after getCallbacks call above
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);

// Generate the proxy class and create a proxy instance.
// 通过 Enhancer 生成代理对象,并设置回调
return createProxyClassAndInstance(enhancer, callbacks);
}
catch (CodeGenerationException | IllegalArgumentException ex) {
throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
": Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Throwable ex) {
// TargetSource.getTarget() failed
throw new AopConfigException("Unexpected AOP exception", ex);
}
}

定位: org.springframework.aop.framework.CglibAopProxy#createProxyClassAndInstance

1
2
3
4
5
6
7
8
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
enhancer.setInterceptDuringConstruction(false);
enhancer.setCallbacks(callbacks);
// 生成代理类以及创建代理
return (this.constructorArgs != null && this.constructorArgTypes != null ?
enhancer.create(this.constructorArgTypes, this.constructorArgs) :
enhancer.create());
}

CglibAopProxy#getCallbacks

定位: org.springframework.aop.framework.CglibAopProxy#getCallbacks

被代理方法的回调

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
// Parameters used for optimization choices...
// 对于 expose-proxy 属性的处理,是否暴露当前对象为 ThreadLocal 模式,在当前上下文中能够进行引用
boolean exposeProxy = this.advised.isExposeProxy();
boolean isFrozen = this.advised.isFrozen();
boolean isStatic = this.advised.getTargetSource().isStatic();

// Choose an "aop" interceptor (used for AOP calls).
// 将拦截器封装在 DynamicAdvisedInterceptor 中
Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);

// Choose a "straight to target" interceptor. (used for calls that are
// unadvised but can return this). May be required to expose the proxy.
Callback targetInterceptor;
if (exposeProxy) {
targetInterceptor = (isStatic ?
new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
}
else {
targetInterceptor = (isStatic ?
new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
}

// Choose a "direct to target" dispatcher (used for
// unadvised calls to static targets that cannot return this).
Callback targetDispatcher = (isStatic ?
new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());

Callback[] mainCallbacks = new Callback[] {
// 将拦截器链加入 Callback 中
aopInterceptor, // for normal advice
targetInterceptor, // invoke target without considering advice, if optimized
new SerializableNoOp(), // no override for methods mapped to this
targetDispatcher, this.advisedDispatcher,
new EqualsInterceptor(this.advised),
new HashCodeInterceptor(this.advised)
};

Callback[] callbacks;

// If the target is a static one and the advice chain is frozen,
// then we can make some optimizations by sending the AOP calls
// direct to the target using the fixed chain for that method.
if (isStatic && isFrozen) {
Method[] methods = rootClass.getMethods();
Callback[] fixedCallbacks = new Callback[methods.length];
this.fixedInterceptorMap = new HashMap<>(methods.length);

// TODO: small memory optimization here (can skip creation for methods with no advice)
for (int x = 0; x < methods.length; x++) {
Method method = methods[x];
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, rootClass);
fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
this.fixedInterceptorMap.put(method, x);
}

// Now copy both the callbacks from mainCallbacks
// and fixedCallbacks into the callbacks array.
callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
this.fixedInterceptorOffset = mainCallbacks.length;
}
else {
callbacks = mainCallbacks;
}
return callbacks;
}

DynamicAdvisedInterceptor#intercept (执行入口)

定位: org.springframework.aop.framework.CglibAopProxy.DynamicAdvisedInterceptor#intercept

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
Object target = null;
TargetSource targetSource = this.advised.getTargetSource();
try {
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// Get as late as possible to minimize the time we "own" the target, in case it comes from a pool...
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// 从advised中获取配置好的AOP通知
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal;
// Check whether we only have one InvokerInterceptor: that is,
// no real advice, but just reflective invocation of the target.
// 如果没有 aop 通知配置,那么直接调用 target 对象的调用方法
if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
// We can skip creating a MethodInvocation: just invoke the target directly.
// Note that the final invoker must be an InvokerInterceptor, so we know
// it does nothing but a reflective operation on the target, and no hot
// swapping or fancy proxying.
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
// 如果拦截器链为空则直接激活原方法
retVal = methodProxy.invoke(target, argsToUse);
}
else {
// We need to create a method invocation...
// 通过cglibMethodInvocation来启动advice通知
retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
}
retVal = processReturnType(proxy, target, method, retVal);
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}

getInterceptorsAndDynamicInterceptionAdvice

定位: org.springframework.aop.framework.AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice

1
2
3
4
5
6
7
8
9
10
11
12
13
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
// 创建一个 method 的缓存对象,在 MethodCacheKey 中实现了 equals 和 hashCode 方法同时还实现了compareTo 方法
MethodCacheKey cacheKey = new MethodCacheKey(method);
List<Object> cached = this.methodCache.get(cacheKey);
// 先从缓存中获取,如果缓存中获取不到,则再调用方法获取,获取之后放入到缓存中
if (cached == null) {
// 调用的是 advisorChainFactory 的 getInterceptorsAndDynamicInterceptionAdvice方法
cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
this, method, targetClass);
this.methodCache.put(cacheKey, cached);
}
return cached;
}

定位: org.springframework.aop.framework.DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, @Nullable Class<?> targetClass) {

// This is somewhat tricky... We have to process introductions first,
// but we need to preserve order in the ultimate list.
// 这里用了一个单例模式 获取 DefaultAdvisorAdapterRegistry 实例
// 在 Spring 中把每一个功能都分的很细,每个功能都会有相应的类去处理 符合单一职责原则的地方很多 这也是值得我们借鉴的一个地方
// AdvisorAdapterRegistry 这个类的主要作用是将 Advice 适配为 Advisor 将 Advisor 适配为对应的 MethodInterceptor
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
Advisor[] advisors = config.getAdvisors();
// 创建一个初始大小为 之前获取到的 通知个数的集合
List<Object> interceptorList = new ArrayList<>(advisors.length);
// 如果目标类为null的话,则从方法签名中获取目标类
Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
// 判断目标类是否存在引介增强,通常为 false
Boolean hasIntroductions = null;

// 循环目标方法匹配的通知
for (Advisor advisor : advisors) {
// 如果是 PointcutAdvisor 类型的实例
if (advisor instanceof PointcutAdvisor) {
// Add it conditionally.
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
// 如果提前进行过切点的匹配了或者当前的 Advisor 适用于目标类
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
boolean match;
//检测Advisor是否适用于此目标方法
if (mm instanceof IntroductionAwareMethodMatcher) {
if (hasIntroductions == null) {
hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
}
match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
}
else {
match = mm.matches(method, actualClass);
}
if (match) {
// 拦截器链是通过 AdvisorAdapterRegistry 来加入的,这个AdvisorAdapterRegistry 对 advice 织入具备很大的作用
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
// 使用 MethodMatchers 的 matches 方法进行匹配判断
if (mm.isRuntime()) {
// Creating a new object instance in the getInterceptors() method
// isn't a problem as we normally cache created chains.
// 动态切入点则会创建一个 InterceptorAndDynamicMethodMatcher 对象
// 这个对象包含 MethodInterceptor 和 MethodMatcher 的实例
for (MethodInterceptor interceptor : interceptors) {
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
}
else {
// 添加到列表中
interceptorList.addAll(Arrays.asList(interceptors));
}
}
}
}
// 如果是引介增强
else if (advisor instanceof IntroductionAdvisor) {
IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
// 将 Advisor 转换为 Interceptor
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
// 以上两种都不是
else {
// 将 Advisor 转换为 Interceptor
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}

return interceptorList;
}