AOP创建代理与调用

创建代理

给Bean创建代理的地方有两个,存在循环依赖的Bean会调用实现了SmartInstantiationAwareBeanPostProcessor接口的getEarlyBeanReference方法,即Bean的生命周期中第四次调用后置处理器的地方,给有AOP代理的且产生循环依赖先被加载的对象创建AOP代理。若在该处已经设置了动态代理会将beanName加入到earlyProxyReferences集合中,防止第八次调用后置处理器时重复添加动态代理

1
2
3
4
5
6
7
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
this.earlyProxyReferences.put(cacheKey, bean);
return wrapIfNecessary(bean, beanName, cacheKey);
}
}

若Bean有AOP代理,但不存在循环依赖存在循环依赖但后被加载,则AOP代理是在第八次调用后置处理器时,给该Bean创建动态代理的。

1
2
3
4
5
6
7
8
9
10
11
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);// 获取缓存key
if (this.earlyProxyReferences.remove(cacheKey) != bean) {// 若之前循环依赖已创建的动态代理则不再创建且移除
return wrapIfNecessary(bean, beanName, cacheKey);// 若存在动态代理将返回创建动态代理后实例
}
}
return bean;
}
}

这两个地方其实都是调用的wrapIfNecessary方法为加载的Bean创建动态代理的,advisedBeans中对于AOP基础类被标记跳过的类会直接返回原始对象。shouldSkip切面解析时就已经对所有切面类进行了解析,这里会走缓存。接着找到当前Bean的所有匹配切点规则的advisor,然后对当前Bean创建代理对象,不管是否创建代理对象都将其缓存到advisedBeans中。

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
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
// 已被处理过即解析切面时targetSourcedBeans出现过,则是自实现创建动态代理逻辑
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { // 不需要增强直接返回
return bean;
}
// 是否基础的Bean、是否需要跳过的重复判断,因为循环依赖是可以改变bean的,若把bean改成了advisor
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// 根据当前Bean找到匹配的advisor列表
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) { // 当前Bean匹配到了advisor
this.advisedBeans.put(cacheKey, Boolean.TRUE); // 标记为已处理
// 真正创建代理对象
Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass()); // 加入到缓存
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}

从候选通知器中找到当前Bean关联的Advisor列表,然后Advisor进行一个排序,按照AfterThrowingAfterReturningAfterAroundBefore的顺序排列,若有多个切面每个切面内还是按照前面的排序,然后再进行切面之间的排序。因为实际调用的时候是方法递归调用,所以排在前面的方法会后执行

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
public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName); // 找到和当前Bean匹配的advisor
if (advisors.isEmpty()) {
return DO_NOT_PROXY; // 若没找到则不创建代理
}
return advisors.toArray();
}
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
List<Advisor> candidateAdvisors = findCandidateAdvisors(); // 获取所有切面的所有Advisor,这里是从缓存获取
// 切点是否命中当前Bean
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) { // 对advisor进行排序
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
protected List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
// 记录当前正在创建的被代理对象的名称
ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {// 从候选通知器中找到当前Bean关联的advisors
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
} finally {//从线程局部变量中清除当前正在创建的beanName的代理对象名称
ProxyCreationContext.setCurrentProxiedBeanName(null);
}
}
}

首先通过AspectJ进行类级别的过滤初筛,若不匹配则直接返回,若PointcutgetMethodMatcher()TrueMethodMatcher则匹配所有方法。这里其实就是将Advisor中的切点表达式与Bean进行匹配。

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
public abstract class AopUtils {
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
if (advisor instanceof IntroductionAdvisor) {// 判断advisor是否为IntroductionAdvisor
return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
} else if (advisor instanceof PointcutAdvisor) { // 判断advisor是否实现了PointcutAdvisor
PointcutAdvisor pca = (PointcutAdvisor) advisor;
return canApply(pca.getPointcut(), targetClass, hasIntroductions); // 找到真正能用的增强器
} else {
return true;
}
}
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
Assert.notNull(pc, "Pointcut must not be null");
if (!pc.getClassFilter().matches(targetClass)) { // 通过AspectJ进行类级别过滤(初筛)
return false;
}
// 进行方法级别过滤(精筛),若pc.getMethodMatcher()返回TrueMethodMatcher则匹配所有方法
MethodMatcher methodMatcher = pc.getMethodMatcher();
if (methodMatcher == MethodMatcher.TRUE) {
return true;
}
// 判断匹配器是否为IntroductionAwareMethodMatcher,只有AspectJExpressionPointCut才会实现这个接口
IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
}
Set<Class<?>> classes = new LinkedHashSet<>(); // 用于保存targetClass的class对象
if (!Proxy.isProxyClass(targetClass)) { // 判断当前class是不是代理的class对象
classes.add(ClassUtils.getUserClass(targetClass)); // 加入到集合中去
}
// 获取到targetClass所实现的接口的class对象,然后加入到集合中
classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
for (Class<?> clazz : classes) { // 循环所有的class对象
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz); // 通过class获取到所有的方法
for (Method method : methods) { // 遍历方法挨个匹配
// 通过methodMatcher.matches来匹配方法
if (introductionAwareMethodMatcher != null ?
// 通过切点表达式进行匹配 AspectJ方式
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
// 通过方法匹配器进行匹配 内置aop接口方式
methodMatcher.matches(method, targetClass)) {
// 只要有1个方法匹配上了就创建代理
return true;
}
}
}
return false;
}
}

通过@Before@Around@After@AfterReturning@AfterThrowing等注解的方法配置的切点,最终的初筛精筛都是调用的AspectJExpressionPointcutmatches方法,其匹配实现是AspectJ来完成的。初筛是通过couldMatchJoinPointsInType方法,精筛是通过matchesMethodExecution方法,通过切点表达式与类和方法进行匹配。

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
public class AspectJExpressionPointcut extends AbstractExpressionPointcut implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware {
public boolean matches(Class<?> targetClass) { // 初筛
PointcutExpression pointcutExpression = obtainPointcutExpression();
try {
try {
return pointcutExpression.couldMatchJoinPointsInType(targetClass);
} catch (ReflectionWorldException ex) {
PointcutExpression fallbackExpression = getFallbackPointcutExpression(targetClass);
if (fallbackExpression != null) {
return fallbackExpression.couldMatchJoinPointsInType(targetClass);
}
}
} catch (Throwable ex) {}
return false;
}
private PointcutExpression obtainPointcutExpression() {
if (getExpression() == null) {
throw new IllegalStateException("Must set property 'expression' before attempting to match");
}
if (this.pointcutExpression == null) {
this.pointcutClassLoader = determinePointcutClassLoader();
this.pointcutExpression = buildPointcutExpression(this.pointcutClassLoader);
}
return this.pointcutExpression;
}
private PointcutExpression buildPointcutExpression(@Nullable ClassLoader classLoader) {
PointcutParser parser = initializePointcutParser(classLoader);
PointcutParameter[] pointcutParameters = new PointcutParameter[this.pointcutParameterNames.length];
for (int i = 0; i < pointcutParameters.length; i++) {
pointcutParameters[i] = parser.createPointcutParameter(this.pointcutParameterNames[i], this.pointcutParameterTypes[i]);
}
return parser.parsePointcutExpression(replaceBooleanOperators(resolveExpression()),this.pointcutDeclarationScope, pointcutParameters);
}
public boolean matches(Method method, Class<?> targetClass, boolean hasIntroductions) { // 精筛
obtainPointcutExpression();
ShadowMatch shadowMatch = getTargetShadowMatch(method, targetClass);
if (shadowMatch.alwaysMatches()) {
return true;
} else if (shadowMatch.neverMatches()) {
return false;
} else {
if (hasIntroductions) {
return true;
}
RuntimeTestWalker walker = getRuntimeTestWalker(shadowMatch);
return (!walker.testsSubtypeSensitiveVars() || walker.testTargetInstanceOfResidue(targetClass));
}
}
}

完成该Bean的所有方法和所有的切点匹配工作后,做存在匹配的切点,则通过ProxyFactory代理工厂来为该Bean创建动态代理。若@EnableAspectJAutoProxy(proxyTargetClass = true)则表示无论该Bean是否实现接口都通过Cglib的方式来创建代理。若未设置该属性,则判断该Bean是否继承接口,若继承接口则使用JDK动态代理,否则使用Cglib动态代理。

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
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) {
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
}
ProxyFactory proxyFactory = new ProxyFactory(); //创建一个代理对象工厂
proxyFactory.copyFrom(this);
// 为proxyFactory设置创建jdk代理还是cglib代理,若设置了<aop:aspectj-autoproxy proxy-target-class="true"/>不会进if,说明强制使用cglib
if (!proxyFactory.isProxyTargetClass()) {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true); // 内部设置的,配置类就会设置这个属性
} else { // 检查有没有接口
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
// 把specificInterceptors数组中的Advisor转化为数组形式的
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors); // 为代理工厂加入通知器,
proxyFactory.setTargetSource(targetSource); // 设置targetSource对象
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
// 代表之前是否筛选advise,因为继承了AbstractAdvisorAutoProxyCreator,且之前调用了findEligibleAdvisors进行筛选,所以是true
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
return proxyFactory.getProxy(getProxyClassLoader()); //真正的创建代理对象
}
}

这里创建动态代理会根据是否指定ProxyTargetClass=true以及有没有接口来决定使用JDK动态代理还是Cglib动态代理

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
public class ProxyFactory extends ProxyCreatorSupport {
public Object getProxy(@Nullable ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader); // createAopProxy()用来获取代理工厂
}
}
public class ProxyCreatorSupport extends AdvisedSupport {
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
}
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
// 判断是否前置指定使用cglib代理ProxyTargetClass=true或者没有接口
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
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.");
}
// 所targetClass是接口则使用jdk代理
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config); // cglib代理
} else {
return new JdkDynamicAopProxy(config); // 动态代理
}
}
}

代理类调用

代理创建时已经将增强器Advisors赋予了代理类,在执行时只需将这些增强器应用到被代理的类上即可,对于JDK动态代理的类来说,当执行具体方法时,会调用JdkDynamicAopProxyinvoke方法,对于Cglib动态代理的类来说,当执行具体方法时,会调用CglibAopProxyDynamicAdvisedInterceptorintercept方法。

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
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
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 {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {// 若执行代理对象的equals方法不需要代理
return equals(args[0]);
} else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {// 若执行的是hashCode方法不需要代理
return hashCode();
}
// 若执行的class对象是DecoratingProxy则不会对其应用切面进行方法的增强,返回源目标类型
else if (method.getDeclaringClass() == DecoratingProxy.class) {
return AopProxyUtils.ultimateTargetClass(this.advised);
}
// 若目标对象实现的Advised接口,则不会对其应用切面进行方法的增强,直接执行方法
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() && method.getDeclaringClass().isAssignableFrom(Advised.class)) {
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
if (this.advised.exposeProxy) { // 暴露代理对象到线程变量中
oldProxy = AopContext.setCurrentProxy(proxy); // 把代理对象暴露到线程变量中
setProxyContext = true;
}
target = targetSource.getTarget(); // 获取目标对象
Class<?> targetClass = (target != null ? target.getClass() : null); // 获取目标对象的class
// 把AOP的advisor全部转化为拦截器,通过责任链模式依次调用
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
if (chain.isEmpty()) { // 若拦截器链为空,通过反射直接调用执行
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
} else {
// 创建一个方法调用对象
MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
retVal = invocation.proceed(); // 调用执行
}
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target && returnType != Object.class && returnType.isInstance(proxy) && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
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 {
if (target != null && !targetSource.isStatic()) {
targetSource.releaseTarget(target);
}
if (setProxyContext) {
AopContext.setCurrentProxy(oldProxy);
}
}
}
}

Cglib动态代理后续调用逻辑与JDK动态代理是一样的

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
class CglibAopProxy implements AopProxy, Serializable {
private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {
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) {
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal;
if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = methodProxy.invoke(target, argsToUse);
} else {
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) {
AopContext.setCurrentProxy(oldProxy);
}
}
}
}
}

其中的this.advised.exposeProxy判断是暴露代理对象线程本地变量中,需搭配@EnableAspectJAutoProxy(exposeProxy = true)一起使用,若有两个方法inittransfer都被设置了代理,但在代理方法中通过this调用另一个代理方法时,该方法不会被代理执行,这时就需要通过AopContext.currentProxy()来配合使用才能是该方法被代理执行,事务方法调用事务方法时就是这样来设置的。

1
2
3
4
5
6
7
8
9
10
11
@Component
@EnableAspectJAutoProxy(exposeProxy = true)
public class Car implements CarSuper {
public void init() {
System.out.println("car init ...");
((CarSuper)AopContext.currentProxy()).transfer();
}
public void transfer() {
System.out.println("Car transfer...");
}
}

第一次调用代理方法时会将该方法与该类上的Advisor列表一一匹配,并将匹配到的Advisor转换成拦截器MethodInterceptor,然后放入缓存,再次调用时直接从缓存中获取。

1
2
3
4
5
6
7
8
9
10
11
public class AdvisedSupport extends ProxyConfig implements Advised {
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
MethodCacheKey cacheKey = new MethodCacheKey(method);
List<Object> cached = this.methodCache.get(cacheKey);
if (cached == null) {
cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(this, method, targetClass);
this.methodCache.put(cacheKey, cached);
}
return cached;
}
}

Advisor中封装的Advice实现了MethodInterceptor拦截器,则直接强制类型转换,否则通过AdvisorAdapter进行转换。内置了MethodBeforeAdviceAdapterAfterReturningAdviceAdapterThrowsAdviceAdapter三个适配器。

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
public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {
private final List<AdvisorAdapter> adapters = new ArrayList<>(3);
public DefaultAdvisorAdapterRegistry() {
registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
registerAdvisorAdapter(new AfterReturningAdviceAdapter());
registerAdvisorAdapter(new ThrowsAdviceAdapter());
}
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, @Nullable Class<?> targetClass) {
List<Object> interceptorList = new ArrayList<Object>(config.getAdvisors().length);
Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
for (Advisor advisor : config.getAdvisors()) {
if (advisor instanceof PointcutAdvisor) {
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
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) {
IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
} else {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
return interceptorList;
}
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
List<MethodInterceptor> interceptors = new ArrayList<>(3);
Advice advice = advisor.getAdvice();
if (advice instanceof MethodInterceptor) {
interceptors.add((MethodInterceptor) advice);
}
for (AdvisorAdapter adapter : this.adapters) {
if (adapter.supportsAdvice(advice)) {
interceptors.add(adapter.getInterceptor(advisor));
}
}
if (interceptors.isEmpty()) {
throw new UnknownAdviceTypeException(advisor.getAdvice());
}
return interceptors.toArray(new MethodInterceptor[0]);
}
}

内置的三个适配器实现都很简单,就是获取到具体的advice然后再转换成具体的拦截器。

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
class AfterReturningAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof AfterReturningAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
AfterReturningAdvice advice = (AfterReturningAdvice) advisor.getAdvice();
return new AfterReturningAdviceInterceptor(advice);
}
}
class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof MethodBeforeAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
return new MethodBeforeAdviceInterceptor(advice);
}
}
class ThrowsAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof ThrowsAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
return new ThrowsAdviceInterceptor(advisor.getAdvice());
}
}

最终将匹配到的拦截器链以及目标方法等信息包装为ReflectiveMethodInvocation执行它的proceed方法,这里的invokeJoinpoint()就是调用连接点被代理的方法本身

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
public Object proceed() throws Throwable {
// 从-1开始,结束条件执行目标方法是下标=拦截器的长度-1,即执行到最后一个拦截器时
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint(); // 当执行到最后一个拦截器的时候才会进入
}
// 获取集合当前需要运行的拦截器
Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
InterceptorAndDynamicMethodMatcher dm = (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
} else {
return proceed();
}
} else {// 执行拦截器方法
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
protected Object invokeJoinpoint() throws Throwable {
return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments);
}
}

首先调用ExposeInvocationInterceptor,一般AOP代理时都会创建一个,然后加入到列表头部,mi.proceed()又回到了ReflectiveMethodInvocation中。

1
2
3
4
5
6
7
8
9
10
11
public class ExposeInvocationInterceptor implements MethodInterceptor, PriorityOrdered, Serializable {
public Object invoke(MethodInvocation mi) throws Throwable {
MethodInvocation oldInvocation = invocation.get();
invocation.set(mi); // 记录当前正在执行的拦截器
try {
return mi.proceed();
} finally {
invocation.set(oldInvocation);
}
}
}

异常通知AspectJAfterThrowingAdvice

1
2
3
4
5
6
7
8
9
10
11
12
13
public class AspectJAfterThrowingAdvice extends AbstractAspectJAdvice implements MethodInterceptor, AfterAdvice, Serializable {
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
} catch (Throwable ex) {
Method handlerMethod = getExceptionHandler(ex);
if (handlerMethod != null) {
invokeHandlerMethod(mi, ex, handlerMethod);
}
throw ex;
}
}
}

前置通知MethodBeforeAdviceInterceptor

1
2
3
4
5
6
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
return mi.proceed();
}
}

返回通知AfterReturningAdviceInterceptor

1
2
3
4
5
6
7
public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {
public Object invoke(MethodInvocation mi) throws Throwable {
Object retVal = mi.proceed();
this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
return retVal;
}
}

后置AspectJAfterAdvice

1
2
3
4
5
6
7
8
9
public class AspectJAfterAdvice extends AbstractAspectJAdvice implements MethodInterceptor, AfterAdvice, Serializable {
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
} finally {
invokeAdviceMethod(getJoinPointMatch(), null, null);
}
}
}

环绕通知AspectJAroundAdvice

1
2
3
4
5
6
7
8
9
10
11
public class AspectJAroundAdvice extends AbstractAspectJAdvice implements MethodInterceptor, Serializable {
public Object invoke(MethodInvocation mi) throws Throwable {
if (!(mi instanceof ProxyMethodInvocation)) {
throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
}
ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;
ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
JoinPointMatch jpm = getJoinPointMatch(pmi);
return invokeAdviceMethod(pjp, jpm, null, null);
}
}