AOP-AspectJ注解源码解析

1.示例

public class Main {
    public static void main(String[] args) {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("spring-aop-test.xml");

        TestInterface test = (TestInterface) applicationContext.getBean("test");
        test.dosomeTest();
        System.out.println("-----");
        test.doOtherTest();
        System.out.println("-----");
        test.a();
        test.b();
    }
}

@Aspect
public class AspectConfig {
    /**
     * 如何定义一个切点?
     * 切点位置:com.xl.code 包下的所有class 的所有 test结尾的方法。
     */
    @Pointcut(value = "execution(* com.wz.spring..*.*Test(..))")
    public void test(){}


    /**
     * 定义一个前置通知
     */
    @Before(value = "test()")
    public void beforeAdvice() {
        System.out.println("before advice");
    }


    /**
     * 定义一个后置通知
     */
    @After(value = "test()")
    public void afterAdvice() {
        System.out.println("after advice");
    }


    /**
     * 定义一个环绕通知
     */
    @Around(value = "execution(* com.wz.spring..*.*Test(..))")
    public void aroundAdvice(ProceedingJoinPoint joinPoint) {
        try {
            System.out.println("around advice begin");
            joinPoint.proceed();
            System.out.println("around advice end");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}






public class TestImpl implements TestInterface {
    @Override
    public void dosomeTest() {
        System.out.println("dosomeTest execute");
    }

    @Override
    public void doOtherTest() {
        System.out.println("doOtherTest execute");
    }

    @Override
    public void a() {
        System.out.println("a function execute");
    }

    @Override
    public void b() {
        System.out.println("b function execute");
    }
}

配置文件:




    

    
    


输出结果:

around advice begin
before advice
dosomeTest execute
after advice
around advice end
-----
around advice begin
before advice
doOtherTest execute
after advice
around advice end
-----
a function execute
b function execute

2.

AopNamespaceHandler

    public void init() {
        // In 2.0 XSD as well as in 2.5+ XSDs
        registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
        registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
        registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());

        // Only in 2.0 XSD: moved to context namespace in 2.5+
        registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
    }
class AspectJAutoProxyBeanDefinitionParser implements BeanDefinitionParser {

    /**
     * @param element 包装  标签数据。
     * @param parserContext 它持有一个   readerContext  ,readerContext 它又持有 registry 也就是咱们的 BeanFactory
     */
    @Override
    @Nullable
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);
        extendBeanDefinition(element, parserContext);
        return null;
    }

2.1 AopNamespaceUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary

    public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
            ParserContext parserContext, Element sourceElement) {

        BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(
                parserContext.getRegistry(), parserContext.extractSource(sourceElement));
        useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
        registerComponentIfNecessary(beanDefinition, parserContext);
    }
    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
            BeanDefinitionRegistry registry, @Nullable Object source) {

        return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
    }
    //参数一:固定类型 AnnotationAwareAspectJAutoProxyCreator  很关键的class,
    // 咱们的Aop功能 全靠这个class了
    //参数二:Spring容器
    //参数三:element
    @Nullable
    private static BeanDefinition registerOrEscalateApcAsRequired(
            Class cls, BeanDefinitionRegistry registry, @Nullable Object source) {

        Assert.notNull(registry, "BeanDefinitionRegistry must not be null");

        //判断容器内是否有 名称 是AUTO_PROXY_CREATOR_BEAN_NAME BD
        // 一般不会走这里,走这里主要原因是 自定义 注解解析器了
        if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
            BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
            if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
                int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
                int requiredPriority = findPriorityForClass(cls);
                if (currentPriority < requiredPriority) {
                    apcDefinition.setBeanClassName(cls.getName());
                }
            }
            return null;
        }

        //创建了一个BD,并且设置class 是 AnnotationAwareAspectJAutoProxyCreator  
        // 最后将这个bd 注册到 容器中了
        RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
        beanDefinition.setSource(source);
        beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
        beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
        return beanDefinition;
    }

再来看看AopNamespaceUtils#useClassProxyingIfNecessary

    // 参数一:Spring容器
    // 参数二:aop标签
    private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry, @Nullable Element sourceElement) {
        if (sourceElement != null) {
            // proxy-target-class 标签属性:true 表示 AOP 底层实现
            // 采用 cglib,默认这个属性是false
            boolean proxyTargetClass = Boolean.parseBoolean(sourceElement.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE));
            if (proxyTargetClass) {
                //配置了 proxy-target-class 并且值是 true
                //获取出来AOP相关的这个BD,向这个BD里面添加一个属性 proxyTargetClass=true
                AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
            }
            //expose-proxy 作用就是 将 当前代理对象 暴露到 上下文内,
            // 方便代理对象内部的真实对象 拿到 代理对象。
            boolean exposeProxy = Boolean.parseBoolean(sourceElement.getAttribute(EXPOSE_PROXY_ATTRIBUTE));
            if (exposeProxy) {
                //获取出来AOP相关的这个BD,向这个BD里面添加一个属性 exposeProxy = true
                AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
            }
        }
    }

3.AnnotationAwareAspectJAutoProxyCreator

3.1 AbstractAutoProxyCreator作为InstantiationAwareBeanPostProcessor

这是个短路操作

    @Override
    public Object postProcessBeforeInstantiation(Class beanClass, String beanName) {
        Object cacheKey = getCacheKey(beanClass, beanName);

        if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
            if (this.advisedBeans.containsKey(cacheKey)) {
                return null;
            }
            if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return null;
            }
        }

        // Create proxy here if we have a custom TargetSource.
        // Suppresses unnecessary default instantiation of the target bean:
        // The TargetSource will handle target instances in a custom fashion.
        TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
        if (targetSource != null) {
            if (StringUtils.hasLength(beanName)) {
                this.targetSourcedBeans.add(beanName);
            }
            Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
            Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        }

        return null;
    }

在 AbstractAutowireCapableBeanFactory#createBean()中doCreateBean()创建实例之前:

        try {
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            //可以通过后处理器,在这一步返回一个代理实例对象..注意,这里的代理对象不是Spring AOP 逻辑实现的地方。
            //instantiation 实例化不要和init 搞混。
            //后处理器调用点:创建实例之前的一个调用点。
            // 它的另外一个作用就是对AOP提供了支持,在这里会将一些不需要被代理的Bean进行标记
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            //条件成立会形成一个短路操作,这里直接返回了.
            if (bean != null) {
                return bean;
            }
        }

3.2 AbstractAutoProxyCreator作为BeanPostProcessor

这个调用位置是在初始化实例后调用的:

    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        }
        else {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            //后处理器调用点:BeforeInitialization   初始化之前的后处理器调用点
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            //后处理器调用点:AfterInitialization 初始化之后的后处理器的调用点
            //典型应用:Spring AOP的实现
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }
 
 

来看看其实现的方法:

    /**
     * @param bean Spring容器完全初始化完毕的实例对象
     * @param beanName
     * Create a proxy with the configured interceptors if the bean is
     * identified as one to proxy by the subclass.
     * @see #getAdvicesAndAdvisorsForBean
     */
    @Override
    public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
        if (bean != null) {
            //cacheKey 大部分情况下 都是 beanName
            Object cacheKey = getCacheKey(bean.getClass(), beanName);
            //防止重复代理某个bean实例。这里A B循环依赖,且需要AOP代理,
             // 则B处理属性A时,已经将A的原始对象放入到了earlyProxyReferences,并且生成了A的AOP代理对象,所以不需要重复生成。
            if (this.earlyProxyReferences.remove(cacheKey) != bean) {
                // AOP操作入口
                return wrapIfNecessary(bean, beanName, cacheKey);

            }

        }
        return bean;
    }

earlyProxyReferences,这里A B循环依赖,且需要AOP代理,则B处理属性A时,已经将A的原始对象放入到了earlyProxyReferences,并且生成了A的AOP代理对象,所以不需要重复生成。

3.2.1 earlyProxyReferences作用分析(AbstractAutoProxyCreator作为SmartInstantiationAwareBeanPostProcessor)

    /**
     * 为了避免重复将某个bean生成代理对象...
     * 1.普通路径
     * 2.bean 与 bean 之间形成依赖时,也会提前创建代理对象。
     */
    private final Map earlyProxyReferences = new ConcurrentHashMap<>(16);

循环依赖:

  • 一级缓存,singletonObjects,存储所有已创建完毕的单例 Bean (完整的 Bean)
  • 二级缓存,earlySingletonObjects,存储所有仅完成实例化,但还未进行属性注入和初始化的 Bean
  • 三级缓存,singletonFactories,存储能建立这个 Bean 的一个工厂ObjectFactory,通过工厂ObjectFactory#getObject能获取这个 Bean,延迟化 Bean 的生成,工厂生成的 Bean 会塞入二级缓存

getBean()步骤:

  • getSingleton(beanName) 依次从三个缓存中获取
  • 实例化
  • addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  • 属性注入
  • 初始化

一个大致过程: getBean(A),AB循环依赖

  • A执行属性注入,这个时候 A 发现需要注入 B,所以去 getBean(B),此时又会走一遍上面描述的逻辑。
  • 到了 B 的属性注入这一步,此时 B 调用 getBean(A),这时候一级缓存里面找不到,但是发现 A 正在创建中的,于是去二级缓存找,发现没找到,于是去三级缓存找,然后找到了。
    并且通过上面提前在三级缓存里暴露的工厂得到 A,然后将这个工厂从三级缓存里删除,并将 A 加入到二级缓存中。(这里getBean()就返回了,不会走后面创建Bean的生命周期过程。)
    然后结果就是 B 属性注入成功。(这里如果是AOP循环依赖,会返回代理对象。)
    紧接着 B 调用 initializeBean 初始化,最终返回,此时 B 已经被加到了一级缓存里 。
  • 这时候就回到了 A 的属性注入,此时注入了 B,接着执行初始化,最后 A 也会被加到一级缓存里,且从二级缓存中删除 A。

ObjectFactory实际是:

addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));

AbstractAutowireCapableBeanFactory#getEarlyBeanReference

    protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
        Object exposedObject = bean;
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                    SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                    exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                }
            }
        }
        return exposedObject;
    }

AbstractAutoProxyCreator#getEarlyBeanReference

    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) {
        Object cacheKey = getCacheKey(bean.getClass(), beanName);
        // 这里放入的是原始的beanName对应的原始的bean
        this.earlyProxyReferences.put(cacheKey, bean);
        // 这里返回的是bean的代理对象
        return wrapIfNecessary(bean, beanName, cacheKey);
    }

3.3 AbstractAutowireCapableBeanFactory#doCreateBean对于返回Bean的处理

    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.
        //包装对象,内部最核心的字段就是咱们的真实实例。它提供了一些额外的接口方法,比如 属性访问器
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            // FactoryBean#getObject()匹配,避免重复创建,直接从这里获取
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            //该方法创建出来真实的bean实例,并且将其包装到BeanWrapper实例中。
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        Object bean = instanceWrapper.getWrappedInstance();
        Class beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        // Allow post-processors to modify the merged bean definition.
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    //后处理器调用点:合并bd信息,因为接下来就是populate处理依赖了..
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }

        // Eagerly cache singletons to be able to resolve circular references
        // even when triggered by lifecycle interfaces like BeanFactoryAware.
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isTraceEnabled()) {
                logger.trace("Eagerly caching bean '" + beanName +
                        "' to allow for resolving potential circular references");
            }
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
            //处理当前实例的依赖数据...依赖注入在这一步完成的。
            populateBean(beanName, mbd, instanceWrapper);
            //生命周期中的初始化方法的调用。
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        }
        catch (Throwable ex) {
            if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
                throw (BeanCreationException) ex;
            }
            else {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
            }
        }

        if (earlySingletonExposure) {
            Object earlySingletonReference = getSingleton(beanName, false);
            //条件成立:说明当前bean实例 从 2级缓存获取到了...
            //说明产生循环依赖了...3级缓存 当前对象的ObjectFactory.getObject() 被调用过
            if (earlySingletonReference != null) {
                //条件成立有几种情况?
                //1.当前“真实实例”不需要被代理
                //2.当前“实例”已经被代理过了...是在ObjectFactory.getObject() 方法调用时 实现的增强代理。
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                }
                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    //获取依赖当前bean的 其它beanName
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                    for (String dependentBean : dependentBeans) {
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }
                    //为什么有问题?
                    //因为咱们当前对象的AOP操作是在 当前方法的 initializeBean 这个方法完成的。
                    //在这之前 外部其它bean持有到的当前的 “bean实例” 都是尚未增强的。
                    if (!actualDependentBeans.isEmpty()) {
                        throw new BeanCurrentlyInCreationException(beanName,
                                "Bean with name '" + beanName + "' has been injected into other beans [" +
                                StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                "] in its raw version as part of a circular reference, but has eventually been " +
                                "wrapped. This means that said other beans do not use the final version of the " +
                                "bean. This is often the result of over-eager type matching - consider using " +
                                "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        // Register bean as disposable.
        try {
            //判断当前bean实例是否需要注册 析构回调。当容器销毁时,会给当前bean的析构方法进行回调。
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }

        return exposedObject;
    }

getBean(A),AB循环依赖

  • A执行属性注入,这个时候 A 发现需要注入 B,所以去 getBean(B),此时又会走一遍上面描述的逻辑。
  • 到了 B 的属性注入这一步,此时 B 调用 getBean(A),这时候一级缓存里面找不到,但是发现 A 正在创建中的,于是去二级缓存找,发现没找到,于是去三级缓存找,然后找到了。
    并且通过上面提前在三级缓存里暴露的工厂得到 A,然后将这个工厂从三级缓存里删除,并将 A 加入到二级缓存中。(这里getBean()就返回了,不会走后面创建Bean的生命周期过程。)
    然后结果就是 B 属性注入成功。(这里如果是AOP循环依赖,会返回代理对象。)
    紧接着 B 调用 initializeBean 初始化,最终返回,此时 B 已经被加到了一级缓存里 。
  • 这时候就回到了 A 的属性注入,此时注入了 B,接着执行初始化,最后 A 也会被加到一级缓存里,且从二级缓存中删除 A。

这里特别关注一下doCreateBean()最后(产生循环依赖时,earlySingletonReference 不为null)返回的Bean到底是啥?

  • 1)A和B没有进行AOP代理,所以exposedObject与bean都是原生的Bean,二级缓存里面也是直接返回该原生Bean就行
  • 2)A和B进行了AOP代理,但是A -> getBean(B) -> getBean(A)时已经从三级缓存调用AbstractAutoProxyCreator#getEarlyBeanReference创建了AOP代理,所以exposedObject与bean都是原生的Bean,二级缓存里面也是直接返回该原生Bean的AOP代理对象就行

4.AbstractAutoProxyCreator#wrapIfNecessary

    protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
        // 条件一般不成立,因为咱们很少使用TargetSourceCreator 去创建对象。 BeforeInstantiation阶段。
        if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
            return bean;
        }

        // 条件成立:说明当前beanName对应的对象 不需要被增强处理,判断是在 BeforeInstantiation阶段 做的。
        if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
            return bean;
        }

        //条件一:isInfrastructureClass 判断当前bean类型是否是 基础框架 的类型,这个类型的实例 不能被增强
        //条件二:shouldSkip 判断当前beanName是否是 .ORIGINAL 结尾,如果是这个结尾 则跳过增强逻辑。
        if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return bean;
        }

        // Create proxy if we have advice.
        // 查找适合当前bean实例Class的通知
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);

        // 条件成立:说明 上面方法 有查询到 适合当前class的通知
        if (specificInterceptors != DO_NOT_PROXY) {
            this.advisedBeans.put(cacheKey, Boolean.TRUE);

            //创建代理对象,根据查询到的 通知 !
            // 参数一:目标对象
            // 参数二:beanName
            // 参数三:匹配当前 目标对象 clazz 的Advisor数据。
            // 参数四:目标对象。
            Object proxy = createProxy(
                    bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));

            // 保存代理对象类型。
            this.proxyTypes.put(cacheKey, proxy.getClass());
            //返回代理对象
            return proxy;
        }

        //执行到这里,说明当前bean不需要被增强。
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        //直接返回原实例。
        return bean;
    }

4.1 AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean

    protected Object[] getAdvicesAndAdvisorsForBean(
            Class beanClass, String beanName, @Nullable TargetSource targetSource) {
        // 查询合适当前类型的 增强 通知.
        List advisors = findEligibleAdvisors(beanClass, beanName);

        if (advisors.isEmpty()) {
            return DO_NOT_PROXY;
        }
        //转换成数组 返回。
        return advisors.toArray();
    }
    protected List findEligibleAdvisors(Class beanClass, String beanName) {
        // 获取到当前项目内所有可以使用的 Advisor
        List candidateAdvisors = findCandidateAdvisors();

        // 将上一步获取到的全部 Advisor 做筛选,筛选出来适合自己当前类型的 Advisor
        List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);


        // 在这一步 会在 index 0 的位置 添加一个 ADVISOR。
        extendAdvisors(eligibleAdvisors);


        if (!eligibleAdvisors.isEmpty()) {
            eligibleAdvisors = sortAdvisors(eligibleAdvisors);
        }

        return eligibleAdvisors;
    }

4.1.1 AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors

AnnotationAwareAspectJAutoProxyCreator#initBeanFactory

    @Override
    protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        super.initBeanFactory(beanFactory);
        if (this.aspectJAdvisorFactory == null) {
            this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
        }
        this.aspectJAdvisorsBuilder =
                new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
    }

可以看到aspectJAdvisorFactory 是ReflectiveAspectJAdvisorFactory,aspectJAdvisorsBuilder 是BeanFactoryAspectJAdvisorsBuilderAdapter。

    protected List findCandidateAdvisors() {
        // Add all the Spring advisors found according to superclass rules.
        // 查询出来 继承Advisor类型 然后注册到容器内的 BD ,对应的bean实例。
        List advisors = super.findCandidateAdvisors();

        // Build Advisors for all AspectJ aspects in the bean factory.
        if (this.aspectJAdvisorsBuilder != null) {
            // 提取添加@Aspect注解类上面定义的 Advisor 信息
            advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
        }
        return advisors;
    }

super就是AbstractAdvisorAutoProxyCreator#findCandidateAdvisors

    protected List findCandidateAdvisors() {
        Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
        return this.advisorRetrievalHelper.findAdvisorBeans();
    }
    public List findAdvisorBeans() {
        // Determine list of advisor bean names, if not cached already.
        String[] advisorNames = this.cachedAdvisorBeanNames;
        if (advisorNames == null) {

            // Do not initialize FactoryBeans here: We need to leave all regular beans
            // uninitialized to let the auto-proxy creator apply to them!
            // 通过 bf 查询 出来 BD 配置的 class 是 Advisor 子类 的 BeanName
            advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                    this.beanFactory, Advisor.class, true, false);
            this.cachedAdvisorBeanNames = advisorNames;
        }

        if (advisorNames.length == 0) {
            return new ArrayList<>();
        }

        List advisors = new ArrayList<>();
        for (String name : advisorNames) {
            // 咱们当前 retrievalHelper 是 Adapter 包装的,真正的逻辑 在 Adapter里面
            if (isEligibleBean(name)) {
                if (this.beanFactory.isCurrentlyInCreation(name)) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Skipping currently created advisor '" + name + "'");
                    }
                }
                else {
                    try {
                        // 使用 Spring 容器查询出来当前这个Advisor类型的实例。
                        advisors.add(this.beanFactory.getBean(name, Advisor.class));
                    }
                    catch (BeanCreationException ex) {
                        Throwable rootCause = ex.getMostSpecificCause();
                        if (rootCause instanceof BeanCurrentlyInCreationException) {
                            BeanCreationException bce = (BeanCreationException) rootCause;
                            String bceBeanName = bce.getBeanName();
                            if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
                                if (logger.isTraceEnabled()) {
                                    logger.trace("Skipping advisor '" + name +
                                            "' with dependency on currently created bean: " + ex.getMessage());
                                }
                                // Ignore: indicates a reference back to the bean we're trying to advise.
                                // We want to find advisors other than the currently created bean itself.
                                continue;
                            }
                        }
                        throw ex;
                    }
                }
            }
        }
        return advisors;
    }

核心是BeanFactoryAspectJAdvisorsBuilderAdapter#buildAspectJAdvisors

    private class BeanFactoryAspectJAdvisorsBuilderAdapter extends BeanFactoryAspectJAdvisorsBuilder {

        public BeanFactoryAspectJAdvisorsBuilderAdapter(
                ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {

            super(beanFactory, advisorFactory);
        }

        @Override
        protected boolean isEligibleBean(String beanName) {
            return AnnotationAwareAspectJAutoProxyCreator.this.isEligibleAspectBean(beanName);
        }
    }

BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors

    public List buildAspectJAdvisors() {
        List aspectNames = this.aspectBeanNames;

        // 条件成立:说明 缓存内没有 advisor信息..需要一个 一个 的 提取出来。
        if (aspectNames == null) {
            synchronized (this) {
                aspectNames = this.aspectBeanNames;
                if (aspectNames == null) {


                    // 保存 通过@Aspect 注解定义的 Advisor 数据
                    List advisors = new ArrayList<>();

                    // 添加@Aspect注解的BeanName
                    aspectNames = new ArrayList<>();

                    // 获取出来Spring容器内全部的 beanName
                    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                            this.beanFactory, Object.class, true, false);

                    // 遍历所有beanName
                    for (String beanName : beanNames) {

                        if (!isEligibleBean(beanName)) {
                            continue;
                        }

                        // We must be careful not to instantiate beans eagerly as in this case they
                        // would be cached by the Spring container but would not have been weaved.
                        // 当bean标签是 parent 类型的时候,class可以是null。
                        Class beanType = this.beanFactory.getType(beanName);
                        if (beanType == null) {
                            continue;
                        }


                        // 查询当前类型 或者 父类 父父类 ... 是否有 @Aspect 注解,如果有 说明当前类型是 Aspect 类型。
                        if (this.advisorFactory.isAspect(beanType)) {
                            aspectNames.add(beanName);

                            // Aspect 元数据
                            AspectMetadata amd = new AspectMetadata(beanType, beanName);


                            // 正常情况下,AjType都是 PerClauseKind.SINGLETON ,其它情况,咱们不考虑了..属于 AspectJ高级用法。
                            if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {

                                // 使用工厂模式 管理 Aspect元数据 关联的 真实 @Aspect注解的 实例对象
                                MetadataAwareAspectInstanceFactory factory =
                                        new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);

                                // ReflectiveAspectJAdvisorFactory# getAdvisors
                                // 这个方法返回 指定添加了 @Aspect 注解 的class相关的 Advisor 信息。
                                List 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 {
                                // Per target or per this.
                                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));
                            }
                        }
                    }

                    // 将刚刚 for循环处理的 打了 @Aspect 注解的 beanName 缓存起来,表示 提取Advisor工作已经做过了。
                    this.aspectBeanNames = aspectNames;
                    return advisors;
                }
            }
        }

        if (aspectNames.isEmpty()) {
            return Collections.emptyList();
        }


        List advisors = new ArrayList<>();
        for (String aspectName : aspectNames) {
            List cachedAdvisors = this.advisorsCache.get(aspectName);
            if (cachedAdvisors != null) {
                advisors.addAll(cachedAdvisors);
            }
            else {
                MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
                advisors.addAll(this.advisorFactory.getAdvisors(factory));
            }
        }
        return advisors;
    }

其中最核心的是ReflectiveAspectJAdvisorFactory#getAdvisors

    @Override
    public List getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
        // 获取 @Aspect 标签的 类的 class
        Class aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
        // 获取 @Aspect 标签的 beanName
        String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
        validate(aspectClass);

        // We need to wrap the MetadataAwareAspectInstanceFactory with a decorator
        // so that it will only instantiate once.
        // 别管它 包装... 咱认为 这个 就是 普通 的 就行。
        MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
                new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);


        List advisors = new ArrayList<>();
        // getAdvisorMethods(aspectClass) 获取出来 @before @after @around ... 这些注解的方法。
        // 不包括 @pointcut 注解的方法。
        for (Method method : getAdvisorMethods(aspectClass)) {
            // Prior to Spring Framework 5.2.7, advisors.size() was supplied as the declarationOrderInAspect
            // to getAdvisor(...) to represent the "current position" in the declared methods list.
            // However, since Java 7 the "current position" is not valid since the JDK no longer
            // returns declared methods in the order in which they are declared in the source code.
            // Thus, we now hard code the declarationOrderInAspect to 0 for all advice methods
            // discovered via reflection in order to support reliable advice ordering across JVM launches.
            // Specifically, a value of 0 aligns with the default value used in
            // AspectJPrecedenceComparator.getAspectDeclarationOrder(Advisor).

            // 这个方法执行完之后,就会将 当前 method 包装成为 Advisor 数据。
            Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, 0, aspectName);

            if (advisor != null) {
                advisors.add(advisor);
            }
        }

        // If it's a per target aspect, emit the dummy instantiating aspect.
        if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
            Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
            advisors.add(0, instantiationAdvisor);
        }

        // Find introduction fields.
        for (Field field : aspectClass.getDeclaredFields()) {
            Advisor advisor = getDeclareParentsAdvisor(field);
            if (advisor != null) {
                advisors.add(advisor);
            }
        }

        // 返回从当前 @Aspect 注解 类 的 提取出来的 advisor 数据。
        return advisors;
    }

重点关注ReflectiveAspectJAdvisorFactory#getAdvisor

    @Override
    @Nullable
    public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,
            int declarationOrderInAspect, String aspectName) {

        validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());

        // 获取切点信息..
        AspectJExpressionPointcut expressionPointcut = getPointcut(
                candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());

        // 条件成立:说明当前方法 上定义的 注解 无法创建出来对应的 Advisor...
        if (expressionPointcut == null) {
            return null;
        }



        //参数一:expressionPointcut 切点表达式
        //参数二:candidateAdviceMethod  当前方法,内部会把当前方法 封装成为 advice,里边再说。
        //参数三:AdvisorFactory 构建Advisor的工厂,里边再说..
        //参数四:aspectInstanceFactory 通过它可以拿到 @Aspect 注解实例 | 拿到元数据
        //参数五:declarationOrderInAspect ...
        //参数六:aspectName  ... 添加了 @Aspect 当前class BeanName
        return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
                this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
    }
    @Nullable
    private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class candidateAspectClass) {

        // 提取出来当前方法上定义的 AspectJ注解信息。
        AspectJAnnotation aspectJAnnotation =
                AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);

        // 条件成立:说明当前方法上面 未定义 指定类型的这些注解..更不要说 Pointcut 信息了...
        if (aspectJAnnotation == null) {
            return null;
        }


        AspectJExpressionPointcut ajexp =
                new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class[0]);
        // 使用aspectJAnnotation 解析出来的 切点表达式
        ajexp.setExpression(aspectJAnnotation.getPointcutExpression());

        if (this.beanFactory != null) {
            ajexp.setBeanFactory(this.beanFactory);
        }

        return ajexp;
    }
    protected static AspectJAnnotation findAspectJAnnotationOnMethod(Method method) {
        // 检查当前方法 是否有这些注解...
        for (Class clazz : ASPECTJ_ANNOTATION_CLASSES) {

            AspectJAnnotation foundAnnotation = findAnnotation(method, (Class) clazz);

            if (foundAnnotation != null) {
                return foundAnnotation;
            }

        }

        return null;
    }

    /**
     * @param method 检查的当前方法
     * @param toLookFor 需要检查的注解类型
     */
    @Nullable
    private static  AspectJAnnotation findAnnotation(Method method, Class toLookFor) {
        // 提取出来 Annotation 数据..
        A result = AnnotationUtils.findAnnotation(method, toLookFor);

        // 条件成立:说明当前方法上面定义了 指定类型的 注解
        if (result != null) {
            // 包装类型成为 AspectJ 类型注解。
            return new AspectJAnnotation<>(result);
        }
        else {
            return null;
        }

    }

来看看AspectJAnnotation类:

        public AspectJAnnotation(A annotation) {
            this.annotation = annotation;
            // 将Annotation类型转换为 对应 的 枚举
            this.annotationType = determineAnnotationType(annotation);
            try {
                // 解析出来当前注解上定义的 切点表达式
                this.pointcutExpression = resolveExpression(annotation);
                // 一般情况下 argNames 咱们不配置,除非使用到 运行时匹配。
                Object argNames = AnnotationUtils.getValue(annotation, "argNames");
                this.argumentNames = (argNames instanceof String ? (String) argNames : "");
            }
            catch (Exception ex) {
                throw new IllegalArgumentException(annotation + " is not a valid AspectJ annotation", ex);
            }
        }
        private static final String[] EXPRESSION_ATTRIBUTES = new String[] {"pointcut", "value"};

        private static Map, AspectJAnnotationType> annotationTypeMap = new HashMap<>(8);

        static {
            annotationTypeMap.put(Pointcut.class, AspectJAnnotationType.AtPointcut);
            annotationTypeMap.put(Around.class, AspectJAnnotationType.AtAround);
            annotationTypeMap.put(Before.class, AspectJAnnotationType.AtBefore);
            annotationTypeMap.put(After.class, AspectJAnnotationType.AtAfter);
            annotationTypeMap.put(AfterReturning.class, AspectJAnnotationType.AtAfterReturning);
            annotationTypeMap.put(AfterThrowing.class, AspectJAnnotationType.AtAfterThrowing);
        }

分析一下InstantiationModelAwarePointcutAdvisorImpl

    //参数一:expressionPointcut 切点表达式
    //参数二:candidateAdviceMethod  当前方法,内部会把当前方法 封装成为 advice,里边再说。
    //参数三:AdvisorFactory 构建Advisor的工厂,里边再说..
    //参数四:aspectInstanceFactory 通过它可以拿到 @Aspect 注解实例 | 拿到元数据
    //参数五:declarationOrderInAspect ...
    //参数六:aspectName  ... 添加了 @Aspect 当前class BeanName
    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();
        // 增强逻辑方法 添加了 @Before ....那些方法
        this.aspectJAdviceMethod = aspectJAdviceMethod;
        this.aspectJAdvisorFactory = aspectJAdvisorFactory;
        this.aspectInstanceFactory = aspectInstanceFactory;
        this.declarationOrder = declarationOrder;
        this.aspectName = aspectName;

        // 正常情况 不走这个分支... AOP 高级应用时走的...
        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;
            this.lazy = false;
            // 创建出来 Advice 对象,Advice 和 Advisor 的关系,是一一对应的关系。
            // Spring 中 每个Advisor 内部一定是持有一个 Advice 的。

            // advice 内部最重要的数据 是 当前method,因为 增强逻辑,最终还是要通过反射的方式 调用回当前method
            //        还有 aspectInstanceFactory 通过这个Factory获取到 添加 @Aspect 注解的实例,有了 实例 和 目标方法,才能反射调用。
            this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);

        }
    }
    private Advice instantiateAdvice(AspectJExpressionPointcut pointcut) {
        // 参数一:当前Advisor内部包装的 添加了 @Before .... 的方法
        // 参数二:pointcut 该方法注解上定义的 切点表达式
        // 参数三:aspectInstanceFactory
        // 参数四:declarationOrder
        Advice advice = this.aspectJAdvisorFactory.getAdvice(this.aspectJAdviceMethod, pointcut,
                this.aspectInstanceFactory, this.declarationOrder, this.aspectName);

        return (advice != null ? advice : EMPTY_ADVICE);
    }

上面调用的是ReflectiveAspectJAdvisorFactory#getAdvice

    public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut,
            MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
        // 获取当前@Before... 方法的 添加了 @Aspect 注解的类
        Class candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();

        validate(candidateAspectClass);


        // 提取出来当前方法上定义的 @Aspect 注解信息
        AspectJAnnotation aspectJAnnotation =
                AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);

        if (aspectJAnnotation == null) {
            return null;
        }


        // If we get here, we know we have an AspectJ method.
        // Check that it's an AspectJ-annotated class

        // 判断当前Class是否是 添加了 @Aspect 注解的 Class
        if (!isAspect(candidateAspectClass)) {
            throw new AopConfigException("Advice must be declared inside an aspect type: " +
                    "Offending method '" + candidateAdviceMethod + "' in class [" +
                    candidateAspectClass.getName() + "]");
        }


        if (logger.isDebugEnabled()) {
            logger.debug("Found AspectJ method: " + candidateAdviceMethod);
        }

        // 最终springAdvice 会保存一个 指定类型的 advice
        AbstractAspectJAdvice springAdvice;

        switch (aspectJAnnotation.getAnnotationType()) {

            // 切点信息,无法生成advice
            case AtPointcut:
                if (logger.isDebugEnabled()) {
                    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())) {
                    springAdvice.setReturningName(afterReturningAnnotation.returning());
                }
                break;

            case AtAfterThrowing:
                springAdvice = new AspectJAfterThrowingAdvice(
                        candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
                AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation();
                if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {
                    springAdvice.setThrowingName(afterThrowingAnnotation.throwing());
                }
                break;
            default:
                throw new UnsupportedOperationException(
                        "Unsupported advice type on method: " + candidateAdviceMethod);
        }

        // Now to configure the advice...
        springAdvice.setAspectName(aspectName);
        springAdvice.setDeclarationOrder(declarationOrder);

        // 从当前添加AspectJ 注解的方法上 提取参数名称。
        String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);
        if (argNames != null) {
            springAdvice.setArgumentNamesFromStringArray(argNames);
        }

        // 营养价值有限,逻辑特复杂...
        springAdvice.calculateArgumentBindings();

        return springAdvice;
    }

4.1.2 AbstractAdvisorAutoProxyCreator#findAdvisorsThatCanApply

    protected List findAdvisorsThatCanApply(
            List candidateAdvisors, Class beanClass, String beanName) {

        ProxyCreationContext.setCurrentProxiedBeanName(beanName);
        try {
            return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
        }
        finally {
            ProxyCreationContext.setCurrentProxiedBeanName(null);
        }
    }

核心逻辑在AopUtils#findAdvisorsThatCanApply中

    public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) {
        // 条件成立:说明当前Spring没有定义Advisor
        if (candidateAdvisors.isEmpty()) {
            return candidateAdvisors;
        }


        // 匹配当前Clazz的 advisors 信息..
        List eligibleAdvisors = new ArrayList<>();

        // 不考虑 引介增强..
        for (Advisor candidate : candidateAdvisors) {
            if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
                eligibleAdvisors.add(candidate);
            }
        }

        // 假设:false。
        boolean hasIntroductions = !eligibleAdvisors.isEmpty();


        for (Advisor candidate : candidateAdvisors) {
            if (candidate instanceof IntroductionAdvisor) {
                // already processed
                continue;
            }

            // 判断当前advisor 是否匹配当前clazz
            if (canApply(candidate, clazz, hasIntroductions)) {
                eligibleAdvisors.add(candidate);
            }

        }

        // 返回的都是匹配当前clazz的 advisors
        return eligibleAdvisors;
    }

    public static boolean canApply(Advisor advisor, Class targetClass, boolean hasIntroductions) {
        if (advisor instanceof IntroductionAdvisor) {
            return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
        }

        // 绝大部分情况 是这个分支,因为咱们创建的 advisor 是 InstantiationModelAwarePointcutAdvisorImpl 类型。
        else if (advisor instanceof PointcutAdvisor) {
            PointcutAdvisor pca = (PointcutAdvisor) advisor;
            // 判断当前pointcut 是否 匹配 当前clazz
            return canApply(pca.getPointcut(), targetClass, hasIntroductions);

        }
        else {
            // It doesn't have a pointcut so we assume it applies.
            return true;
        }
    }
    public static boolean canApply(Pointcut pc, Class targetClass, boolean hasIntroductions) {
        Assert.notNull(pc, "Pointcut must not be null");
        // 条件成立:clazz不满足 切点定义。因为后面是 判断 method 是否匹配的 逻辑... clazz都不匹配 ,后面逻辑不用看了..
        if (!pc.getClassFilter().matches(targetClass)) {
            return false;
        }

        // 获取 方法匹配器
        MethodMatcher methodMatcher = pc.getMethodMatcher();

        // 因为 TrueMethodMatcher 方法匹配器 匹配所有方法,所以 直接返回true
        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) {
            introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
        }


        // 保存 当前目标 对象clazz + 包括自身实现的接口 + 目标对象 父类 父父类.... 的接口
        Set> classes = new LinkedHashSet<>();


        // 这个if 就是确保 classes 内存储的数据 包括 目标对象的 clazz ,而不是 代理类clazz。
        // 这里表示如果不是jdk代理类,就要取出cglib代理类代理的类
        if (!Proxy.isProxyClass(targetClass)) {
            classes.add(ClassUtils.getUserClass(targetClass));
        }
        //包括自身实现的接口 + 目标对象 父类 父父类.... 的接口
        classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));


        // 整个for循环 会检查 当前目标clazz 上级+自身方法 接口 的所有方法 看看是否会被 方法匹配器 匹配,如果有一个方法匹配成功,就说明
        // 目标clazz 需要被 AOP 代理增强!
        for (Class clazz : classes) {
            // 获取当前clazz内定义的method
            Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
            for (Method method : methods) {
                if (introductionAwareMethodMatcher != null ?
                        introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
                        methodMatcher.matches(method, targetClass)) {
                    return true;
                }
            }
        }

        // 执行到这,说明当前clazz 内 没有方法被匹配成功..就不需要创建代理clazz了。
        return false;
    }

4.1.3 AspectJAwareAdvisorAutoProxyCreator#extendAdvisors

在这一步会在 index 0 的位置添加一个 ADVISOR。

    public static boolean makeAdvisorChainAspectJCapableIfNecessary(List advisors) {
        // Don't add advisors to an empty list; may indicate that proxying is just not required
        if (!advisors.isEmpty()) {
            boolean foundAspectJAdvice = false;
            for (Advisor advisor : advisors) {
                // Be careful not to get the Advice without a guard, as this might eagerly
                // instantiate a non-singleton AspectJ aspect...
                if (isAspectJAdvice(advisor)) {
                    foundAspectJAdvice = true;
                    break;
                }
            }
            if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {
                advisors.add(0, ExposeInvocationInterceptor.ADVISOR);
                return true;
            }
        }
        return false;
    }

4.2 AbstractAutoProxyCreator#createProxy

    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);
        }

        // 创建代理对象 的 工厂,它必须持有 创建 代理clazz 的生产资料。
        // 1.目标对象
        // 2.advisor信息
        ProxyFactory proxyFactory = new ProxyFactory();

        // 复制一些信息 到 proxyFactory
        proxyFactory.copyFrom(this);

        // 条件成立:说明咱们没有使用 xml配置修改过 aop proxyTargetClass 为 true.
        if (!proxyFactory.isProxyTargetClass()) {
            // 是否自动设置 proxyTargetClass = true ?
            // 如果bd定义内 有  preserveTargetClass = true ,那么这个bd对应的clazz 创建代理时 必须使用 cglib。
            if (shouldProxyTargetClass(beanClass, beanName)) {
                proxyFactory.setProxyTargetClass(true);
            }
            else {
                // 根据目标类 判定是否可以使用 JDK 动态代理..
                evaluateProxyInterfaces(beanClass, proxyFactory);
            }
        }

        // 参数一:beanName
        // 参数二:specificInterceptors 匹配当前目标对象clazz 的 advisors
        Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);


        // 提供给ProxyFactory advisors信息。
        proxyFactory.addAdvisors(advisors);

        // 提供给 ProxyFactory 目标对象。
        proxyFactory.setTargetSource(targetSource);

        // 留给用户的扩展点
        customizeProxyFactory(proxyFactory);

        proxyFactory.setFrozen(this.freezeProxy);


        if (advisorsPreFiltered()) {
            // 设置为true ,表示传递给 proxyFactory 的这些 Advisors信息 做过基础匹配,classFilter匹配。
            proxyFactory.setPreFiltered(true);
        }


        return proxyFactory.getProxy(getProxyClassLoader());
    }

ProxyFactory -> ProxyConfig#copyFrom

    public void copyFrom(ProxyConfig other) {
        Assert.notNull(other, "Other ProxyConfig object must not be null");
        // true 使用 cglib 生成代理类   ,默认是 false.
        this.proxyTargetClass = other.proxyTargetClass;
        this.optimize = other.optimize;

        // true 表示创建出来的代理对象,执行方法的时候 会将 “代理对象” 暴露到 上下文内。
        this.exposeProxy = other.exposeProxy;

        this.frozen = other.frozen;
        this.opaque = other.opaque;
    }
    protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
        // Handle prototypes correctly...

        // 公共 方法拦截器,Spring提供给使用者的扩展点,默认是没有的。
        Advisor[] commonInterceptors = resolveInterceptorNames();

        // 全部的 方法拦截器
        List allInterceptors = new ArrayList<>();

        if (specificInterceptors != null) {
            allInterceptors.addAll(Arrays.asList(specificInterceptors));
            if (commonInterceptors.length > 0) {
                if (this.applyCommonInterceptorsFirst) {
                    allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
                }
                else {
                    allInterceptors.addAll(Arrays.asList(commonInterceptors));
                }
            }
        }
        if (logger.isTraceEnabled()) {
            int nrOfCommonInterceptors = commonInterceptors.length;
            int nrOfSpecificInterceptors = (specificInterceptors != null ? specificInterceptors.length : 0);
            logger.trace("Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors +
                    " common interceptors and " + nrOfSpecificInterceptors + " specific interceptors");
        }

        Advisor[] advisors = new Advisor[allInterceptors.size()];
        for (int i = 0; i < allInterceptors.size(); i++) {
            advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
        }

        return advisors;
    }

 
 
    @Override
    public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {
        if (adviceObject instanceof Advisor) {
            return (Advisor) adviceObject;
        }
        if (!(adviceObject instanceof Advice)) {
            throw new UnknownAdviceTypeException(adviceObject);
        }

        Advice advice = (Advice) adviceObject;
        if (advice instanceof MethodInterceptor) {
            // So well-known it doesn't even need an adapter.
            return new DefaultPointcutAdvisor(advice);
        }

        for (AdvisorAdapter adapter : this.adapters) {
            // Check that it is supported.
            if (adapter.supportsAdvice(advice)) {
                return new DefaultPointcutAdvisor(advice);
            }
        }

        throw new UnknownAdviceTypeException(advice);
    }
    public DefaultAdvisorAdapterRegistry() {
        registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
        registerAdvisorAdapter(new AfterReturningAdviceAdapter());
        registerAdvisorAdapter(new ThrowsAdviceAdapter());
    }

最后就是创建动态代理的过程

    public Object getProxy(@Nullable ClassLoader classLoader) {
        return createAopProxy().getProxy(classLoader);
    }

详细过程参见:https://www.jianshu.com/p/0f798b36b733

5.总结

整体流程如下:

  • 向Spring容器注册了一个AnnotationAwareAspectJAutoProxyCreator
  • AnnotationAwareAspectJAutoProxyCreator实现了接口BeanPostProcessor、InstantiationAwareBeanPostProcessor、SmartInstantiationAwareBeanPostProcessor

接下来看看AnnotationAwareAspectJAutoProxyCreator在Bean生命周期的哪个地方起作用:

  • 1)获取beanName(别名或者&打头->去掉&)
  • 2)到缓存中获取共享单实例,单参数getSingleton,主要就是从三级缓存中获取
     2-1)如果发生循环依赖,就会从三级缓存中取出ObjectFactory调用:getEarlyBeanReference()中调用SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference(AnnotationAwareAspectJAutoProxyCreator作为SmartInstantiationAwareBeanPostProcessor在这里提前实现AOP动态代理)
  • 3)缓存中有对应的数据,此时缓存数据可能是普通单实例 也可能是 FactoryBean,所以需要根据name来进行判断,并且返回数据。
  • 4)缓存中没有bean数据,需要创建了
     4-1)处理原型循环依赖
     4-2)父容器查找
     4-3)获取合并后的BeanDefinition,校验:抽象的BD不能创建实例
     4-4)处理depends-on(会先getBean(dep)依赖的bean),如果产生循环依赖,报错(依靠两个Map,一个map是 dependentBeanMap 另一个是 dependenciesForBeanMap)
     4-5)单例创建,重载getSingleton(beanName, ObjectFactory),ObjectFactory -> createBean,然后还调用getObjectForBeanInstance处理可能是FactoryBean的情况
       A)判断当前mbd中的class是否已经加载到jvm,如果未加载,则使用类加载器将classStr加载到Jvm中
       B)对XML标签中定义的lookUp属性进行预处理
       C)短路操作resolveBeforeInstantiation()调用InstantiationAwareBeanPostProcessor 的InstantiationAwareBeanPostProcessor 方法,AnnotationAwareAspectJAutoProxyCreator实现了该方法
       D)创建bean实例对象doCreateBean()
         D-1)createBeanInstance()创建Bean实例
         D-2)applyMergedBeanDefinitionPostProcessors扩展点MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition()方法
         D-3)addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));加入三级缓存
          a) getEarlyBeanReference()中调用SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference
         D-4)populateBean()依赖注入
          a)InstantiationAwareBeanPostProcessor # postProcessAfterInstantiation
          b)autowireByName/ autowireByType
          c)InstantiationAwareBeanPostProcessor # postProcessProperties
          d)进行依赖检查
          e)将依赖注入合并后的pvs 应用到 真实的Bean实例中
         D-5)initializeBean()初始化
          a)invokeAwareMethods
          b)applyBeanPostProcessorsBeforeInitialization扩展点BeanPostProcessor#postProcessBeforeInitialization
          c)invokeInitMethods
          d)applyBeanPostProcessorsAfterInitialization扩展点 BeanPostProcessor#postProcessAfterInitialization(AnnotationAwareAspectJAutoProxyCreator作为BeanPostProcessor,在此实现动态代理,如果发生循环依赖,已经代理过了,此时则不需要重复生成代理)
         D-6)处理产生循环依赖时,真正返回的bean应该是啥(动态代理时需返回代理对象)
     4-6)原型创建
     4-7)其他情况实例创建
  • 5)创建的实例是否与requiredType类型相匹配
  • 6)返回实例

再来看看生成的代理对象的过程(核心逻辑):

  • 1)getAdvicesAndAdvisorsForBean() 查找适合当前bean实例Class的增强
     1-1)findCandidateAdvisors()获取到当前项目内所有可以使用的 Advisor(首先查询出来 继承Advisor类型的Advisor, 然后提取添加@Aspect注解类上面定义的 Advisor:InstantiationModelAwarePointcutAdvisorImpl,包括两部分:切点pointcut和增强instantiatedAdvice(包括AspectJAroundAdvice、AspectJMethodBeforeAdvice、AspectJAfterAdvice等))
     1-2)findAdvisorsThatCanApply()从上一步获取到的全部 Advisor 做筛选,筛选出来适合自己当前类型的 Advisor(首先进行类匹配;其次会检查当前目标clazz 上级+自身方法 接口 的所有方法 看看是否会被 方法匹配器 匹配,如果有一个方法匹配成功,就说明目标clazz 需要被 AOP 代理增强。)
     1-3)在 index 0 的位置 添加一个ExposeInvocationInterceptor.ADVISOR
     1-4)sortAdvisors()排序
  • 2)createProxy() 根据查询得到的增强,创建动态代理对象
     2-1)创建代理对象的工厂ProxyFactory,它必须持有 创建 代理clazz 的生产资料。
     2-2)判定使用JDK还是CGLIB动态代理
     2-3)构建Advisors(如果是MethodInterceptor包装成DefaultPointcutAdvisor,如果是Advisor则直接返回),并设置到ProxyFactory里面;设置目标类(原生Bean)到ProxyFactory中
     2-4)proxyFactory.getProxy()创建动态代理
       A)createAopProxy()返回JdkDynamicAopProxy或者ObjenesisCglibAopProxy,一般情况返回JdkDynamicAopProxy
       B)JdkDynamicAopProxy#getProxy,Proxy.newProxyInstance创建代理对象,并将JdkDynamicAopProxy作为InvocationHandler h传入代理类,代理类所有方法都会交由super.h.invoke()也即JdkDynamicAopProxy#invoke进行处理

最后再来看看动态代理调用过程JdkDynamicAopProxy#invoke:

  • 1)this.advised.exposeProxy 如果是true,就要把当前这个代理对象,暴漏 到Aop上下文内
  • 2)查找匹配该方法的所有增强chain:DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice
     2-1)从ProxyFactory 获取出所有的Advisor
     2-2)遍历Advisor,先进行类匹配,然后进行方法匹配,如果匹配,则获取Advisor中的Advice(AspectJAroundAdvice、AspectJAfterThrowingAdvice、AspectJAfterAdvice是MethodInterceptor,直接返回;AspectJMethodBeforeAdvice、AspectJAfterReturningAdvice需要适配器适配成MethodInterceptor)加入interceptorList链
     2-3)返回interceptorList
  • 3)联合chain包装成ReflectiveMethodInvocation,进行调用
     3-1)ReflectiveMethodInvocation#proceed
      根据currentInterceptorIndex逐个进行调用;
      最终调用至被代理的方法;
     3-2)MethodInterceptor#invoke(this),这里的this就是ReflectiveMethodInvocation
      AspectJAroundAdvice(不需要适配)、AspectJMethodBeforeAdvice等等
     3-3)最后反射调用至被代理的方法

这里注意AspectJMethodBeforeAdvice没有实现MethodInterceptor接口



需要进行适配:

public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {

    private final List adapters = new ArrayList<>(3);


    /**
     * Create a new DefaultAdvisorAdapterRegistry, registering well-known adapters.
     */
    public DefaultAdvisorAdapterRegistry() {
        registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
        registerAdvisorAdapter(new AfterReturningAdviceAdapter());
        registerAdvisorAdapter(new ThrowsAdviceAdapter());
    }

以MethodBeforeAdviceAdapter为例

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);
    }

}

看看 MethodBeforeAdviceInterceptor#invoke

public Object invoke(MethodInvocation mi) throws Throwable {
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
        return mi.proceed();
    }

你可能感兴趣的:(AOP-AspectJ注解源码解析)