Spring AOP创建代理之获取增强器

hresh 427 0

Spring AOP创建代理之获取增强器

在上一篇文章中我们讲解了关于Spring AOP 自定义标签的解析,其中主要是完成了对 AspectJAwareAdvisorAutoProxyCreator 和 AnnotationAwareAspectJAutoProxyCreator 类型的自动注册,我们看一下它们两个的层次接口,如下图所示:

Spring AOP创建代理之获取增强器

从上图的类层次结构图中我们可以发现这两个类是父子关系,那么我们就针对子类 AnnotationAwareAspectJAutoProxyCreator 来进行分析。首先可以看到该类实现了 BeanPostProcessor 接口,而实现 BeanPostProcessor 接口后,当 Spring 加载这个 Bean 时会在实例化前会调用其 postProcessBeforeInstantiation 方法,实例化结束后会调用 postProcesssAfterIntialization 方法,我们对于 AOP 逻辑的分析也由 postProcessBeforeInstantiation 方法开始。

声明:调试案例即为初识Spring AOP一文中的案例

postProcessBeforeInstantiation

首先我们定位到 AbstractAutoProxyCreator 类中,查看其中实现的 postProcessBeforeInstantiation方法:

    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
        //根据给定的bean的class和name构建出个key,格式:beanClassName_beanName
        Object cacheKey = this.getCacheKey(beanClass, beanName);
        //如果未处理过
        if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
            if (this.advisedBeans.containsKey(cacheKey)) {
                return null;
            }

            // 给定的bean类是否代表一个基础设施类,基础设施类则添加到advisedBeans中,或者配置了指定bean
            if (this.isInfrastructureClass(beanClass) || this.shouldSkip(beanClass, beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return null;
            }
        }

        //为bean实例创建目标源。 如果设置,则使用任何TargetSourceCreators。 如果不应该使用自定义TargetSource,则返回null。
        TargetSource targetSource = this.getCustomTargetSource(beanClass, beanName);
        if (targetSource != null) {
            if (StringUtils.hasLength(beanName)) {
                this.targetSourcedBeans.add(beanName);
            }

            Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
            Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        } else {
            return null;
        }
    }

以上内容我们重点关注 shouldSkip()方法,在调试过程中发现,当 beanName 为“host”时,会执行 shouldSkip()方法,进而会创建切面信息。当 beanName 为“ProxyAnnotation2”时,cacheKey 会添加到 advisedBeans 中,这点会在 postProcesssAfterIntialization 方法中有所体现。

那接下来我们对 shouldSkip()方法学习一番,其实现在 AspectJAwareAdvisorAutoProxyCreator 类中:

    protected boolean shouldSkip(Class<?> beanClass, String beanName) {
        List<Advisor> candidateAdvisors = this.findCandidateAdvisors();
        Iterator var4 = candidateAdvisors.iterator();

        Advisor advisor;
        do {
            if (!var4.hasNext()) {
                return super.shouldSkip(beanClass, beanName);
            }

            advisor = (Advisor)var4.next();
        } while(!(advisor instanceof AspectJPointcutAdvisor) || !((AspectJPointcutAdvisor)advisor).getAspectName().equals(beanName));

        return true;
    }

获取增强器

findCandidateAdvisors()方法会查找增强信息,如果无则创建。因为是在 bean 实例化之前,所以需要创建增强信息。通过 findCandidateAdvisors()进行查找,其代码在 AnnotationAwareAspectJAutoProxyCreator 类中被覆写了,具体如下:

    protected List<Advisor> findCandidateAdvisors() {
        // 当使用注解方式配置AOP的时候并不是丢弃了对XML配置的支持,
        // 在这里调用父类方法加载配置文件中的AOP声明
        List<Advisor> advisors = super.findCandidateAdvisors();
        if (this.aspectJAdvisorsBuilder != null) {
            advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
        }

        return advisors;
    }

AnnotationAwareAspectJAutoProxyCreator间接继承了AbstractAdvisorAutoProxyCreator, 在实现获取增强的方法中除了保留父类的获取配置文件中定义的增强外,同时添加了获取 Bean 的注解增强的功能,那么其实现正是由 this.aspectJAdvisorsBuilder.buildAspectJAdvisors()来实现的。

其中 buildAspectJAdvisors()会获取定义的切面信息,并返回给 shouldSkip()方法。该方法在 BeanFactoryAspectJAdvisorsBuilder 类中实现,其定义如下:

public List<Advisor> buildAspectJAdvisors() {
    List<String> aspectNames = this.aspectBeanNames;
    if (aspectNames == null) {
        synchronized(this) {
            aspectNames = this.aspectBeanNames;
            if (aspectNames == null) {
                List<Advisor> advisors = new ArrayList();
                List<String> aspectNames = new ArrayList();
                // 获取所有的beanName
                String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Object.class, true, false);
                String[] var18 = beanNames;
                int var19 = beanNames.length;

                // 循环所有的beanName找出对应的增强方法
                for(int var7 = 0; var7 < var19; ++var7) {
                    String beanName = var18[var7];
                    if (this.isEligibleBean(beanName)) {
                        Class<?> beanType = this.beanFactory.getType(beanName);
                        // 如果存在Aspect注解
                        if (beanType != null && this.advisorFactory.isAspect(beanType)) {
                            aspectNames.add(beanName);
                            AspectMetadata amd = new AspectMetadata(beanType, beanName);
                            if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
                                MetadataAwareAspectInstanceFactory factory = new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
                                // 解析标记Aspect注解中的增强方法
                                List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
                                if (this.beanFactory.isSingleton(beanName)) {
                                    //将增强器存入缓存中,下次可以直接取
                                    this.advisorsCache.put(beanName, classAdvisors);
                                } else {
                                    this.aspectFactoryCache.put(beanName, factory);
                                }

                                advisors.addAll(classAdvisors);
                            } else {
                                if (this.beanFactory.isSingleton(beanName)) {
                                    throw new IllegalArgumentException("Bean with name '" + beanName + "' is a singleton, but aspect instantiation model is not singleton");
                                }

                                MetadataAwareAspectInstanceFactory factory = new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
                                this.aspectFactoryCache.put(beanName, factory);
                                advisors.addAll(this.advisorFactory.getAdvisors(factory));
                            }
                        }
                    }
                }

                this.aspectBeanNames = aspectNames;
                return advisors;
            }
        }
    }

    if (aspectNames.isEmpty()) {
        return Collections.emptyList();
    } else {
        // 记录在缓存中
        List<Advisor> advisors = new ArrayList();
        Iterator var3 = aspectNames.iterator();

        while(var3.hasNext()) {
            String aspectName = (String)var3.next();
            List<Advisor> cachedAdvisors = (List)this.advisorsCache.get(aspectName);
            if (cachedAdvisors != null) {
                advisors.addAll(cachedAdvisors);
            } else {
                MetadataAwareAspectInstanceFactory factory = (MetadataAwareAspectInstanceFactory)this.aspectFactoryCache.get(aspectName);
                advisors.addAll(this.advisorFactory.getAdvisors(factory));
            }
        }

        return advisors;
    }
}

调试过程中的信息如下:

Spring AOP创建代理之获取增强器

Spring AOP创建代理之获取增强器

通过调试可以理解其实现过程如下:

  1. 获取所有 beanName,这一步骤中所有在 beanFactory 中注册的 Bean 都会被提取出来;
  2. 遍历所有的 beanName,并找出声明 AspectJ 注解的类,进行下一步的处理;
  3. 对标记为AspectJ 注解的类进行增强器的提取;
  4. 将提取结果加入缓存。

至此,我们已经完成了 Advisor 的提取,在上面的步骤中最为重要也最为繁杂的就是增强器的获取,而这一切功能委托给了 getAdvisors 方法去实现 this.advisorFactory.getAdvisors(factory);

首先我们看下 BeanFactoryUtils.beanNamesForTypeIncludingAncestors()方法,它主要是将我们之前对 BeanDefinition 的解析和读取的结果提取出来。然后是 this.advisorFactory.isAspect(beanType)方法,该方法在 AbstractAspectJAdvisorFactory 类中实现:

    public boolean isAspect(Class<?> clazz) {
        return this.hasAspectAnnotation(clazz) && !this.compiledByAjc(clazz);
    }

    private boolean hasAspectAnnotation(Class<?> clazz) {
        return AnnotationUtils.findAnnotation(clazz, Aspect.class) != null;
    }

    public static <A extends Annotation> A findAnnotation(Class<?> clazz, @Nullable Class<A> annotationType) {
        if (annotationType == null) {
            return null;
        } else if (!AnnotationFilter.PLAIN.matches(annotationType) && !AnnotationsScanner.hasPlainJavaAnnotationsOnly(clazz)) {
            return (Annotation)MergedAnnotations.from(clazz, SearchStrategy.TYPE_HIERARCHY, RepeatableContainers.none()).get(annotationType).withNonMergedAttributes().synthesize(MergedAnnotation::isPresent).orElse((Object)null);
        } else {
            //判断此Class 是否存在Aspect.class注解
            A annotation = clazz.getDeclaredAnnotation(annotationType);
            if (annotation != null) {
                return annotation;
            } else {
                Class<?> superclass = clazz.getSuperclass();
                return superclass != null && superclass != Object.class ? findAnnotation(superclass, annotationType) : null;
            }
        }
    }

    private boolean compiledByAjc(Class<?> clazz) {
        Field[] var2 = clazz.getDeclaredFields();
        int var3 = var2.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            Field field = var2[var4];
            if (field.getName().startsWith("ajc$")) {
                return true;
            }
        }

        return false;
    }

如果 bean 存在 Aspect.class注解,就可以获取此bean中的增强器了,接着我们来看看 List classAdvisors = this.advisorFactory.getAdvisors(factory); ,该方法在 ReflectiveAspectJAdvisorFactory 类中实现:

public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
    // 获取标记为AspectJ的类
    Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
    // 获取标记为AspectJ的name
    String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
    this.validate(aspectClass);
    MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory = new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
    List<Advisor> advisors = new ArrayList();

    // 对aspectClass的每一个带有注解的方法进行循环(带有PointCut注解的方法除外),取得Advisor,并添加到集合里。
    // (这是里应该是取得Advice,然后取得我们自己定义的切面类中PointCut,组合成Advisor)
    Iterator var6 = this.getAdvisorMethods(aspectClass).iterator();

    while(var6.hasNext()) {
        Method method = (Method)var6.next();
        //将类中的方法封装成Advisor
        Advisor advisor = this.getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
        if (advisor != null) {
            advisors.add(advisor);
        }
    }

    //如果寻找的增强器不为空而且又配置了增强延迟初始化,那么需要在首位加入同步实例化增强器
    if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
        Advisor instantiationAdvisor = new ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
        advisors.add(0, instantiationAdvisor);
    }

    Field[] var12 = aspectClass.getDeclaredFields();
    int var13 = var12.length;

    //获取DeclareParents注解
    for(int var14 = 0; var14 < var13; ++var14) {
        Field field = var12[var14];
        Advisor advisor = this.getDeclareParentsAdvisor(field);
        if (advisor != null) {
            advisors.add(advisor);
        }
    }

    return advisors;
}

调试截图如下:

Spring AOP创建代理之获取增强器

该方法首先完成了对增强器的获取,包括获取注解以及根据注解生成增强的步骤,然后考虑在配置中可能会将增强配置成延迟初始化,那么需要在首位加入同步实例化增强器以保证增强使用之前的实例化,最后是对 DeclareParents 注解的获取,下面分为三个步骤进行介绍。

1、普通增强器的获取

普通增强器的获取逻辑通过 getAdvisor 方法实现,不过在此之前呢需要将所有带注解的 Method 都取出来,该逻辑通过 getAdvisorMethods()实现。

private List<Method> getAdvisorMethods(Class<?> aspectClass) {
    List<Method> methods = new ArrayList();
    ReflectionUtils.doWithMethods(aspectClass, (method) -> {
        // 声明为Pointcut的方法不处理,即不放到 methods中
        if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {
            methods.add(method);
        }

    }, ReflectionUtils.USER_DECLARED_METHODS);
    methods.sort(METHOD_COMPARATOR);
    return methods;
}

public static void doWithMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc, @Nullable ReflectionUtils.MethodFilter mf) {
    // 通过反射获取类中所有的方法
    Method[] methods = getDeclaredMethods(clazz, false);
    Method[] var4 = methods;
    int var5 = methods.length;

    int var6;
    for(var6 = 0; var6 < var5; ++var6) {
        Method method = var4[var6];
        if (mf == null || mf.matches(method)) {
            try {
                mc.doWith(method);
            } catch (IllegalAccessException var9) {
                throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + var9);
            }
        }
    }

    if (clazz.getSuperclass() == null || mf == USER_DECLARED_METHODS && clazz.getSuperclass() == Object.class) {
        if (clazz.isInterface()) {
            Class[] var10 = clazz.getInterfaces();
            var5 = var10.length;

            for(var6 = 0; var6 < var5; ++var6) {
                Class<?> superIfc = var10[var6];
                doWithMethods(superIfc, mc, mf);
            }
        }
    } else {
        doWithMethods(clazz.getSuperclass(), mc, mf);
    }

}

获取到使用注解的 Method 之后,就要遍历执行 getAdvisor(),其定义如下:

public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrderInAspect, String aspectName) {
    this.validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());
    // 获取PointCut信息(主要是PointCut里的表达式)
    // 把Method对象也传进去的目的是,比较Method对象上的注解,是不是下面注解其中一个
    // 如果不是,返回null;如果是,就把取得PointCut内容包装返回
    // 被比较注解:Before.class, Around.class, After.class, AfterReturning.class, AfterThrowing.class, Pointcut.class
    AspectJExpressionPointcut expressionPointcut = this.getPointcut(candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
    // 根据PointCut信息生成增强器
    return expressionPointcut == null ? null : new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod, this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
}

(1)获取切点信息

所谓获取切点信息就是指定注解的表达式信息的获取,如 @Before(value = "rentPointCut()")

private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class<?> candidateAspectClass) {
    // 获取方法上的注解
    // 比较Method对象上的注解,是不是下面注解其中一个,如果不是返回null
    // 被比较注解:Before.class, Around.class, After.class, AfterReturning.class, AfterThrowing.class, Pointcut.class
    AspectJAnnotation<?> aspectJAnnotation = AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
    if (aspectJAnnotation == null) {
        return null;
    } else {
        // 使用AspectJExpressionPointcut 实例封装获取的信息
        AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class[0]);
        // 提取得到的注解中的表达式如:
    // @Pointcut("execution(* com.msdn.bean.Host.rent())")
        ajexp.setExpression(aspectJAnnotation.getPointcutExpression());
        if (this.beanFactory != null) {
            ajexp.setBeanFactory(this.beanFactory);
        }

        return ajexp;
    }
}

详细看下上面方法中使用到的方法 findAspectJAnnotationOnMethod。

protected static AbstractAspectJAdvisorFactory.AspectJAnnotation<?> findAspectJAnnotationOnMethod(Method method) {
    Class[] var1 = ASPECTJ_ANNOTATION_CLASSES;
    int var2 = var1.length;

    for(int var3 = 0; var3 < var2; ++var3) {
        Class<?> clazz = var1[var3];
        // 设置要查找的注解类,看看方法的上注解是不是这些注解其中之一
        AbstractAspectJAdvisorFactory.AspectJAnnotation<?> foundAnnotation = findAnnotation(method, clazz);
        if (foundAnnotation != null) {
            return foundAnnotation;
        }
    }

    return null;
}

其中 ASPECTJ_ANNOTATION_CLASSES 表示注解类数组,用来遍历匹配。我们继续往下查看。

    private static <A extends Annotation> AbstractAspectJAdvisorFactory.AspectJAnnotation<A> findAnnotation(Method method, Class<A> toLookFor) {
        A result = AnnotationUtils.findAnnotation(method, toLookFor);
        return result != null ? new AbstractAspectJAdvisorFactory.AspectJAnnotation(result) : null;
    }

此方法的功能是获取指定方法上的注解并使用 AspectJAnnotation 封装。

(2)根据切点信息生成增强类

所有的增强都有 Advisor 实现类 InstantiationModelAwarePontcutAdvisorImpl 进行统一封装的。我们看下其构造函数:

public InstantiationModelAwarePointcutAdvisorImpl(AspectJExpressionPointcut declaredPointcut, Method aspectJAdviceMethod, AspectJAdvisorFactory aspectJAdvisorFactory, MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {

    this.declaredPointcut = declaredPointcut;
    this.declaringClass = aspectJAdviceMethod.getDeclaringClass();
    this.methodName = aspectJAdviceMethod.getName();
    this.parameterTypes = aspectJAdviceMethod.getParameterTypes();
    this.aspectJAdviceMethod = aspectJAdviceMethod;
    this.aspectJAdvisorFactory = aspectJAdvisorFactory;
    this.aspectInstanceFactory = aspectInstanceFactory;
    this.declarationOrder = declarationOrder;
    this.aspectName = aspectName;
    if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
        Pointcut preInstantiationPointcut = Pointcuts.union(aspectInstanceFactory.getAspectMetadata().getPerClausePointcut(), this.declaredPointcut);
        this.pointcut = new InstantiationModelAwarePointcutAdvisorImpl.PerTargetInstantiationModelPointcut(this.declaredPointcut, preInstantiationPointcut, aspectInstanceFactory);
        this.lazy = true;
    } else {
        this.pointcut = this.declaredPointcut;
        this.lazy = false;
        this.instantiatedAdvice = this.instantiateAdvice(this.declaredPointcut);
    }

}

调试过程中该部分信息如下:

Spring AOP创建代理之获取增强器

通过调试结果可以发现该类的构造函数只是简单地将信息封装在类的实例中,所有的信息单纯地赋值,在实例初始化的过程中还完成了对于增强器的初始化。调试还可以发现不同的增强所体现的逻辑是不同的,比如 @Before(value = "rentPointCut()")与@After(value = "rentPointCut()") 标签的不同就是增强器增强的位置不同,所以就需要不同的增强器来完成不同的逻辑,而根据注解中的信息初始化对应的增强器就是在 instantiateAdvice()方法中实现的。

private Advice instantiateAdvice(AspectJExpressionPointcut pointcut) {
    Advice advice = this.aspectJAdvisorFactory.getAdvice(this.aspectJAdviceMethod, pointcut, this.aspectInstanceFactory, this.declarationOrder, this.aspectName);
    return advice != null ? advice : EMPTY_ADVICE;
}

public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut, MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
    Class<?> candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
    this.validate(candidateAspectClass);
    AspectJAnnotation<?> aspectJAnnotation = AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
    if (aspectJAnnotation == null) {
        return null;
    } else if (!this.isAspect(candidateAspectClass)) {
        throw new AopConfigException("Advice must be declared inside an aspect type: Offending method '" + candidateAdviceMethod + "' in class [" + candidateAspectClass.getName() + "]");
    } else {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Found AspectJ method: " + candidateAdviceMethod);
        }

        Object springAdvice;
        switch(aspectJAnnotation.getAnnotationType()) {
            case AtPointcut:
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Processing pointcut '" + candidateAdviceMethod.getName() + "'");
                }

                return null;
            case AtAround:
                springAdvice = new AspectJAroundAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
                break;
            case AtBefore:
                springAdvice = new AspectJMethodBeforeAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
                break;
            case AtAfter:
                springAdvice = new AspectJAfterAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
                break;
            case AtAfterReturning:
                springAdvice = new AspectJAfterReturningAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
                AfterReturning afterReturningAnnotation = (AfterReturning)aspectJAnnotation.getAnnotation();
                if (StringUtils.hasText(afterReturningAnnotation.returning())) {
                    ((AbstractAspectJAdvice)springAdvice).setReturningName(afterReturningAnnotation.returning());
                }
                break;
            case AtAfterThrowing:
                springAdvice = new AspectJAfterThrowingAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
                AfterThrowing afterThrowingAnnotation = (AfterThrowing)aspectJAnnotation.getAnnotation();
                if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {
                    ((AbstractAspectJAdvice)springAdvice).setThrowingName(afterThrowingAnnotation.throwing());
                }
                break;
            default:
                throw new UnsupportedOperationException("Unsupported advice type on method: " + candidateAdviceMethod);
        }

        ((AbstractAspectJAdvice)springAdvice).setAspectName(aspectName);
        ((AbstractAspectJAdvice)springAdvice).setDeclarationOrder(declarationOrder);
        String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);
        if (argNames != null) {
            ((AbstractAspectJAdvice)springAdvice).setArgumentNamesFromStringArray(argNames);
        }

        ((AbstractAspectJAdvice)springAdvice).calculateArgumentBindings();
        return (Advice)springAdvice;
    }
}

从上述函数代码中可以看到,Spring会根据不同的注解生成不同的增强器,正如代码switch (aspectJAnnotation.getAnnotationType()),根据不同的类型来生成。例如 AtBefore 会对应 AspectJMethodBeforeAdvice。在AspectJMethodBeforeAdvice 中完成了增强逻辑。那接下来,我们一起来分析一下 AspectJMethodBeforeAdvice,也就是 @Before 注解对应的通知实现类。看看它的逻辑是什么样的。

public class AspectJMethodBeforeAdvice extends AbstractAspectJAdvice implements MethodBeforeAdvice, Serializable {
    public AspectJMethodBeforeAdvice(Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {
        super(aspectJBeforeAdviceMethod, pointcut, aif);
    }

    public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
        this.invokeAdviceMethod(this.getJoinPointMatch(), (Object)null, (Throwable)null);
    }

    public boolean isBeforeAdvice() {
        return true;
    }

    public boolean isAfterAdvice() {
        return false;
    }
}

我们重点关注 before 方法,该方法调用了父类中的 invokeAdviceMethod,然后 invokeAdviceMethod 在调用 invokeAdviceMethodWithGivenArgs,最后在 invokeAdviceMethodWithGivenArgs 通过反射执行通知方法。

关于 AspectJMethodBeforeAdvice 就简单介绍到这里吧,至于剩下的几种实现,大家可以自己去看看。

2、增加同步实例化增强器

如果寻找的增强器 不为空而且又配置了增强延迟初始化,那么就需要在首位加入同步实例化增强器。同步实例化增强器 SyntheticInstantiationAdvisor 如下:

    protected static class SyntheticInstantiationAdvisor extends DefaultPointcutAdvisor {
        public SyntheticInstantiationAdvisor(MetadataAwareAspectInstanceFactory aif) {
            super(aif.getAspectMetadata().getPerClausePointcut(), (method, args, target) -> {
                //简单初始化aspect
                aif.getAspectInstance();
            });
        }
    }
3、获取DeclareParents注解

DeclareParents 主要用于引介增强的注解方式的实现,而其实现方式与普通增强很类似,只不过使用 DeclareParentsAdvisor 对功能进行封装。

    private Advisor getDeclareParentsAdvisor(Field introductionField) {
        DeclareParents declareParents = (DeclareParents)introductionField.getAnnotation(DeclareParents.class);
        if (declareParents == null) {
            return null;
        } else if (DeclareParents.class == declareParents.defaultImpl()) {
            throw new IllegalStateException("'defaultImpl' attribute must be set on DeclareParents");
        } else {
            return new DeclareParentsAdvisor(introductionField.getType(), declareParents.value(), declareParents.defaultImpl());
        }
    }

至此关于增强器的获取已结束,现在我们回到 shouldSkip()方法,发现最后它又调用了父类的 shouldSkip()方法,其定义如下:

    protected boolean shouldSkip(Class<?> beanClass, String beanName) {
        return AutoProxyUtils.isOriginalInstance(beanName, beanClass);
    }

    static boolean isOriginalInstance(String beanName, Class<?> beanClass) {
        if (StringUtils.hasLength(beanName) && beanName.length() == beanClass.getName().length() + ".ORIGINAL".length()) {
            return beanName.startsWith(beanClass.getName()) && beanName.endsWith(".ORIGINAL");
        } else {
            return false;
        }
    }

非指定 bean 执行 isOriginalInstance()方法,将不会返回 true。

后续的内容调试过程中并未发现其它内容,那么 postProcessBeforeInstantiation()方法分析到此为止。接下来学习 postProcesssAfterIntialization 方法。

postProcesssAfterIntialization

postProcesssAfterIntialization 方法定义如下:

    public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
        if (bean != null) {
            //根据给定的bean的class和name构建出个key,格式:beanClassName_beanName
            Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
            if (this.earlyProxyReferences.remove(cacheKey) != bean) {
                //如果它适合被代理,则需要封装指定bean 
                return this.wrapIfNecessary(bean, beanName, cacheKey);
            }
        }

        return bean;
    }

在上面的代码中用到了方法 wrapIfNecessary,继续跟踪到方法内部:

```java
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
//如果已经处理过
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
} else if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {// 无需增强,一般是基础设施类
return bean;
} else if (!this.isInfrastructureClass(bean.getClass()) && !this.shouldSkip(bean.getClass(), beanName)) {// 给定的bean类是否代表一个基础设施类,基础设施类不应代理,或者配置了指定bean不需要自动代理
// 获取增强
Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, (TargetSource)null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
//针对增强创建代理
Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
} else {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
} else {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
}

```

调试过程中发现,当 beanName 为“host”时,会获取到增强,具体是通过 getAdvicesAndAdvisorsForBean()方法实现的,其代码在 AbstractAdvisorAutoProxyCreator 类中,如下:

    protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
        List<Advisor> advisors = this.findEligibleAdvisors(beanClass, beanName);
        return advisors.isEmpty() ? DO_NOT_PROXY : advisors.toArray();
    }

    protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
        //查找要在自动代理中使用的所有候选Advisor
        List<Advisor> candidateAdvisors = this.findCandidateAdvisors();
        //搜索给定的候选Advisor,以查找可以应用于指定bean的所有Advisor
        List<Advisor> eligibleAdvisors = this.findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
        this.extendAdvisors(eligibleAdvisors);
        if (!eligibleAdvisors.isEmpty()) {
            eligibleAdvisors = this.sortAdvisors(eligibleAdvisors);
        }

        return eligibleAdvisors;
    }

其中的 findCandidateAdvisors()在 AnnotationAwareAspectJAutoProxyCreator 类中被覆写了。

    protected List<Advisor> findCandidateAdvisors() {
        List<Advisor> advisors = super.findCandidateAdvisors();
        if (this.aspectJAdvisorsBuilder != null) {
            advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
        }

        return advisors;
    }

调试过程中发现获取的增强方法如下图所示:

Spring AOP创建代理之获取增强器

从上述方法和图片可以看出,创建代理主要包含了两个步骤:

  1. 获取增强方法或者增强器;
  2. 根据获取的增强进行代理。

对于指定 bean 的增强方法的获取一定是包含两个步骤,获取所有的增强以及寻找所有增强中使用与 bean 的增强并应用,那么 findCandidateAdvisorsfindAdvisorsThatCanApply 便是做了这两件事情。当然,如果无法找到对应的增强器便返回 DO_NOT_PROXY,其中 DO_NOT_PROXY=null

寻找匹配的增强器

前面讲的获取增强器是发生在 postProcessBeforeInstantiation 方法中,完成了所有增强器的解析,但是对于所有增强器来讲,并不一定都适用于当前的 Bean,所以还需要将 Bean 与增强器相对应,即一对多的关系。那么该处理发生在哪里呢,我们在 getAdvicesAndAdvisorsForBean方法中有提到 findAdvisorsThatCanApply ,该方法就是用来挑选出适合的增强器。

    protected List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
        ProxyCreationContext.setCurrentProxiedBeanName(beanName);

        List var4;
        try {
            // 过滤已经得到的advisors
            var4 = AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
        } finally {
            ProxyCreationContext.setCurrentProxiedBeanName((String)null);
        }

        return var4;
    }

   public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
        if (candidateAdvisors.isEmpty()) {
            return candidateAdvisors;
        } else {
            List<Advisor> eligibleAdvisors = new ArrayList();
            Iterator var3 = candidateAdvisors.iterator();

            while(var3.hasNext()) {
                Advisor candidate = (Advisor)var3.next();
                // 首先处理引介增强
                if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
                    eligibleAdvisors.add(candidate);
                }
            }

            boolean hasIntroductions = !eligibleAdvisors.isEmpty();
            Iterator var7 = candidateAdvisors.iterator();

            // 对于普通bean的处理
            while(var7.hasNext()) {
                Advisor candidate = (Advisor)var7.next();
                if (!(candidate instanceof IntroductionAdvisor) && canApply(candidate, clazz, hasIntroductions)) {
                    eligibleAdvisors.add(candidate);
                }
            }

            return eligibleAdvisors;
        }
    }

findAdvisorsThatCanApply 函数的主要功能是寻找增强器中适用于当前 class 的增强器。引介增强与普通的增强的处理是不一样的,所以分开处理。而对于真正的匹配在 canApply 中实现。

public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
    if (advisor instanceof IntroductionAdvisor) {
        return ((IntroductionAdvisor)advisor).getClassFilter().matches(targetClass);
    } else if (advisor instanceof 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");
    //通过Pointcut的条件判断此类是否能匹配
    if (!pc.getClassFilter().matches(targetClass)) {
        return false;
    } else {
        MethodMatcher methodMatcher = pc.getMethodMatcher();
        if (methodMatcher == MethodMatcher.TRUE) {
            return true;
        } else {
            IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
            if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
                introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher)methodMatcher;
            }

            Set<Class<?>> classes = new LinkedHashSet();
            if (!Proxy.isProxyClass(targetClass)) {
                classes.add(ClassUtils.getUserClass(targetClass));
            }

            classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
            Iterator var6 = classes.iterator();

            while(var6.hasNext()) {
                Class<?> clazz = (Class)var6.next();
                //反射获取类中所有的方法
                Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
                Method[] var9 = methods;
                int var10 = methods.length;

                for(int var11 = 0; var11 < var10; ++var11) {
                    Method method = var9[var11];
                    /根据匹配原则判断该方法是否能匹配Pointcut中的规则,如果有一个方法能匹配,则返回true
                        if (introductionAwareMethodMatcher != null) {
                            if (introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) {
                                return true;
                            }
                        } else if (methodMatcher.matches(method, targetClass)) {
                            return true;
                        }
                }
            }

            return false;
        }
    }
}

首先判断 bean 是否满足切点的规则,如果能满足,则获取 bean 的所有方法,判断是否有方法能匹配规则,有方法匹配规则,就代表此 Advisor 能作用于该 bean,然后将该 Advisor 加入 eligibleAdvisors 集合中。

这里我们重点关注一下匹配规则,即 matches 方法,该方法在 AspectJExpressionPointcut 中实现。

    public boolean matches(Method method, Class<?> targetClass, boolean hasIntroductions) {
        this.obtainPointcutExpression();
        ShadowMatch shadowMatch = this.getTargetShadowMatch(method, targetClass);
        if (shadowMatch.alwaysMatches()) {
            return true;
        } else if (shadowMatch.neverMatches()) {
            return false;
        } else if (hasIntroductions) {
            return true;
        } else {
            RuntimeTestWalker walker = this.getRuntimeTestWalker(shadowMatch);
            return !walker.testsSubtypeSensitiveVars() || walker.testTargetInstanceOfResidue(targetClass);
        }
    }

至此,我们在 postProcesssAfterIntialization 方法中找到了所有匹配 Bean 中的增强器,下一章会讲解代理的创建。

拓展筛选出的增强器列表

findEligibleAdvisors 方法中在执行完 findAdvisorsThatCanApply()方法后,还有一个 extendAdvisors()方法,虽然它做的事情不多,逻辑也比较简单。但是我发现执行完该方法后 eligibleAdvisors 会新增一个对象,因此觉得需要一探究竟。该方法在 AspectJAwareAdvisorAutoProxyCreator 类中,定义如下:

    protected void extendAdvisors(List<Advisor> candidateAdvisors) {
        AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);
    }

    public static boolean makeAdvisorChainAspectJCapableIfNecessary(List<Advisor> advisors) {
        if (!advisors.isEmpty()) {
            boolean foundAspectJAdvice = false;
            Iterator var2 = advisors.iterator();

            while(var2.hasNext()) {
                Advisor advisor = (Advisor)var2.next();
                //检测 advisors 列表中是否存在 AspectJ 类型的 Advisor 或 Advice
                if (isAspectJAdvice(advisor)) {
                    foundAspectJAdvice = true;
                    break;
                }
            }

            if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {
                //向 advisors 列表的首部添加 DefaultPointcutAdvisor
                advisors.add(0, ExposeInvocationInterceptor.ADVISOR);
                return true;
            }
        }

        return false;
    }

makeAdvisorChainAspectJCapableIfNecessary 方法主要的目的是向通知器列表首部添加 DefaultPointcutAdvisor 类型的通知器,也就是 ExposeInvocationInterceptor.ADVISOR。至于添加此种类型增强器的意图,我会在后面文章里说明,这里不便展开。关于 extendAdvisors 这个方法,这里就先说到这了。

总结

本篇文章也接近尾声了,这篇文章有点长,大家看下来应该也挺累的。在学习源码的过程中,我参考了很多资料,最终按照自己学习的进度记录下来的,比如我重点写了关于 postProcessBeforeInstantiation 的使用,以上讲解是根据我调试的顺序进行的,与网上讲的可能会有些出入。不过总算是把主要逻辑弄清楚了,某些细节部分可能没有讲解到。大家在阅读的过程中,如果发现文章中出现错误或不妥之处,这里还请指明,也请多多指教。大家共同学习,一起进步。

参考

《Spring 源码深度解析》- 郝佳

发表评论 取消回复
表情 图片 链接 代码

分享