Spring源码解析之Aop

本文详细解析了SpringBoot如何自动导入并配置Aop,包括AspectJAutoProxyRegistrar的注册与注解解析,以及AnnotationAwareAspectJAutoProxyCreator在Bean实例化前后的处理过程,涉及CGLIB和JDK动态代理的选择以及代理对象的获取和创建。
摘要由CSDN通过智能技术生成

pringBoot集成Spring的Aop只需要导入aop依赖包就能自动实现AOP功能。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
复制代码

SpringBoot是通过自动配置来实现的,所以我们只需要看aop的自动配置AopAutoConfiguration类究竟做了什么

一、SpringBoot自动导入Aop

@Configuration(proxyBeanMethods = false)
//1.spring.aop.auto配置为true才生效
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {

   @Configuration(proxyBeanMethods = false)
   //2.有Advice这个类
   @ConditionalOnClass(Advice.class)
   static class AspectJAutoProxyingConfiguration {

      @Configuration(proxyBeanMethods = false)
      //4.使AOP生效(如果是接口使用JDK代理)
      @EnableAspectJAutoProxy(proxyTargetClass = false)
      //3.spring.aop.proxy-target-class配置为false
      @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",
            matchIfMissing = false)
      static class JdkDynamicAutoProxyConfiguration {

      }

      @Configuration(proxyBeanMethods = false)
      //4.使AOP生效(如果是接口使用Cjlib代理)
      @EnableAspectJAutoProxy(proxyTargetClass = true)
      //3.spring.aop.proxy-target-class配置为true
      @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
            matchIfMissing = true)
      static class CglibAutoProxyConfiguration {

      }

   }

   @Configuration(proxyBeanMethods = false)
   //如果没有Advice只为基础的advisor做动态代理,而忽略应用定义的Advisors,说明项目中我们自定义的切面是不会被AOP代理的。
   @ConditionalOnMissingClass("org.aspectj.weaver.Advice")
   @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
         matchIfMissing = true)
   static class ClassProxyingConfiguration {
        
      ClassProxyingConfiguration(BeanFactory beanFactory) {
         if (beanFactory instanceof BeanDefinitionRegistry) {
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            //注册InfrastructureAdvisorAutoProxyCreator
            AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
            //将InfrastructureAdvisorAutoProxyCreator设置为默认代理类
            AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
         }
      }

   }

}
复制代码

流程如下图:

1.1 AspectJAutoProxyRegistrar

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

   @Override
   public void registerBeanDefinitions(
         AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

      // 1.1.1 注册自动代理类 
      AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
      // 1.1.2 解析注解
      AnnotationAttributes enableAspectJAutoProxy =
            AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
      if (enableAspectJAutoProxy != null) {
         if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
            AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
         }
         if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
            AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
         }
      }
   }

}
复制代码

1.1.1 注册自动代理类

public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
   return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
}
复制代码

注册AnnotationAwareAspectJAutoProxyCreator

public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
      BeanDefinitionRegistry registry, @Nullable Object source) {

   return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
}
复制代码

创建AnnotationAwareAspectJAutoProxyCreatorBeanDefinition并注册进容器,Bean名称:org.springframework.aop.config.internalAutoProxyCreator

private static BeanDefinition registerOrEscalateApcAsRequired(
      Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {

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

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

   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;
}
复制代码

1.1.2 解析注解

//获取@EnableAspectJAutoProxy属性值
AnnotationAttributes enableAspectJAutoProxy =
      AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
if (enableAspectJAutoProxy != null) {
   //1.1.2.1 如果proxyTargetClass为true
   if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
      AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
   }//1.1.2.2 如果exposeProxy为true
   if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
      AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
   }
}
复制代码

1.1.2.1 如果proxyTargetClass为true

控制是基于subclass-based的CGLIB动态代理还是使用基于接口的JDK动态代理 (默认值为false,即默认使用JDK动态代理方式),判断阶段:2.2.2.2.1

public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) {
   if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
      BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
      definition.getPropertyValues().add("proxyTargetClass", Boolean.TRUE);
   }
}
复制代码

1.1.2.2 如果exposeProxy为true

控制代理的暴露方式,解决类内部方法之间调用不能使用代理的场景(默认值为false,如果设置为true的话,我们就可以通过AopContext.currentProxy()很容易拿到当前代理对象)

public static void forceAutoProxyCreatorToExposeProxy(BeanDefinitionRegistry registry) {
   if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
      BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
      definition.getPropertyValues().add("exposeProxy", Boolean.TRUE);
   }
}
复制代码

二、AnnotationAwareAspectJAutoProxyCreator

Spring在创建Bean之前会先判断是否需要创建代理对象AbstractAutowireCapableBeanFactory类的createBean方法

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

   if (logger.isTraceEnabled()) {
      logger.trace("Creating instance of bean '" + beanName + "'");
   }
   RootBeanDefinition mbdToUse = mbd;

   Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
   if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      mbdToUse = new RootBeanDefinition(mbd);
      mbdToUse.setBeanClass(resolvedClass);
   }

   // Prepare method overrides.
   try {
      mbdToUse.prepareMethodOverrides();
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
            beanName, "Validation of method overrides failed", ex);
   }

   try {
      // 给后置处理器一个机会,来生成一个代理对象,代替普通的目标对象。
      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      if (bean != null) {
         return bean;
      }
   }
   catch (Throwable ex) {
      throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
            "BeanPostProcessor before instantiation of bean failed", ex);
   }

   try {
      Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      if (logger.isTraceEnabled()) {
         logger.trace("Finished creating instance of bean '" + beanName + "'");
      }
      return beanInstance;
   }

}
复制代码

判断是否有InstantiationAwareBeanPostProcessor处理器

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
   Object bean = null;
   //
   if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
      // 判断是否有InstantiationAwareBeanPostProcessor处理器
      if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
         Class<?> targetType = determineTargetType(beanName, mbd);
         if (targetType != null) {
            //在Bean实例化之前处理Bean
            bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
            if (bean != null) {
               //如果Bean不为null在Bean实例化之后处理Bean
               bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
            }
         }
      }
      mbd.beforeInstantiationResolved = (bean != null);
   }
   return bean;
}
复制代码

在Bean实例化之前处理Bean

protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
   //获取InstantiationAwareBeanPostProcessor后置处理器处理Bean
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof InstantiationAwareBeanPostProcessor) {
         InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
         Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
         if (result != null) {
            return result;
         }
      }
   }
   return null;
}
复制代码

AnnotationAwareAspectJAutoProxyCreator继承了AbstractAutoProxyCreator

AbstractAutoProxyCreator实现了SmartInstantiationAwareBeanPostProcessor

2.1 AbstractAutoProxyCreator#postProcessBeforeInstantiation 实例化之前处理Bean定义信息

public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
    // 缓存机制
    Object cacheKey = getCacheKey(beanClass, beanName);

    if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
        // 判断该Bean是否已经被增强(advisedBeans为已经增强过的Bean)
        if (this.advisedBeans.containsKey(cacheKey)) {
            return null;
        }
        // 2.1.1 判断是否为基础类型(isInfrastructureClass)或者 2.1.2 判断是否需要跳过的Bean
        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,则在此处创建代理。
    // 这段源码要抑制目标bean的不必要的默认实例化:TargetSource将以自定义方式处理目标实例。
    // 2.1.3 自定义目标资源,对于单实例Bean必定会返回null
    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;
}
复制代码

2.1.1 AnnotationAwareAspectJAutoProxyCreator#isInfrastructureClass:判断是否是需要代理的类

protected boolean isInfrastructureClass(Class<?> beanClass) {
   return (super.isInfrastructureClass(beanClass) ||
         (this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));
}
复制代码

①AbstractAutoProxyCreator#isInfrastructureClass

protected boolean isInfrastructureClass(Class<?> beanClass) {
   //是否是Advice、Pointcut、Advisor、AopInfrastructureBean子类
   boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
         Pointcut.class.isAssignableFrom(beanClass) ||
         Advisor.class.isAssignableFrom(beanClass) ||
         AopInfrastructureBean.class.isAssignableFrom(beanClass);
   if (retVal && logger.isTraceEnabled()) {
      logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");
   }
   return retVal;
}
复制代码

②AbstractAspectJAdvisorFactory#isAspect

public boolean isAspect(Class<?> clazz) {
   return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));
}
复制代码

类上是否有@Aspect注解

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

类属性是否有ajc$为开头的属性名

private boolean compiledByAjc(Class<?> clazz) {
   //类属性是否有ajc$为开头的属性名
   for (Field field : clazz.getDeclaredFields()) {
      if (field.getName().startsWith(AJC_MAGIC)) {
         return true;
      }
   }
   return false;
}
复制代码

2.1.2 AspectJAwareAdvisorAutoProxyCreator#shouldSkip:判断是否需要跳过

protected boolean shouldSkip(Class<?> beanClass, String beanName) {
   // TODO: Consider optimization by caching the list of the aspect names
   // 2.1.2.1 获取增强器
   List<Advisor> candidateAdvisors = findCandidateAdvisors();
   for (Advisor advisor : candidateAdvisors) {
      if (advisor instanceof AspectJPointcutAdvisor &&
            ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {
         return true;
      }
   }
   2.1.2.2 判断目标对象是不是原始对象(没有代理)
   return super.shouldSkip(beanClass, beanName);
}
复制代码

2.1.2.1 获取增强器

protected List<Advisor> findCandidateAdvisors() {
   // 2.1.2.1.1 获取Advisor子类增强器
   List<Advisor> advisors = 
   super.findCandidateAdvisors-->
   // 2.1.2.1.2 获取带有@AspectJ注解增强器
   if (this.aspectJAdvisorsBuilder != null) {
      advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
   }
   return advisors;
}
复制代码

2.1.2.1.1 AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors:获取Advisor子类增强器

protected List<Advisor> findCandidateAdvisors() {
   Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
   //获取增强器
   return this.advisorRetrievalHelper.findAdvisorBeans();
}
复制代码

从容器找出所有Advisor的子类并创建出来

public List<Advisor> findAdvisorBeans() {
   // Determine list of advisor bean names, if not cached already.
   // 确定增强器bean名称的列表(如果尚未缓存)
   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!
      // 不要在这里初始化FactoryBeans:我们需要保留所有未初始化的常规bean,以使自动代理创建者对其应用 
      // 其实这里只是把那些类型为Advisor的Bean都找出来而已
      advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
            this.beanFactory, Advisor.class, true, false);
      this.cachedAdvisorBeanNames = advisorNames;
   }
   // 如果当前IOC容器中没有任何增强器类Bean,直接返回
   if (advisorNames.length == 0) {
      return new ArrayList<>();
   }
   // 有增强器类Bean,循环它们
   List<Advisor> advisors = new ArrayList<>();
   for (String name : advisorNames) {
      if (isEligibleBean(name)) {
         if (this.beanFactory.isCurrentlyInCreation(name)) {
            if (logger.isTraceEnabled()) {
               logger.trace("Skipping currently created advisor '" + name + "'");
            }
         }
         else {
            try {
               // 利用getBean把这些增强器先创建出来
               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();
                  // 这里可能也会引发循环依赖,如果这里正在创建这个增强器了,直接continue
                  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;
}
复制代码

2.1.2.1.2 buildAspectJAdvisors:获取带有@AspectJ注解增强器

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<>();
                aspectNames = new ArrayList<>();
                // 获取IOC容器中的所有Bean
                String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                        this.beanFactory, Object.class, true, false);
                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,因为在这种情况下,IOC容器会缓存它们,但不会被织入增强器
                    // 这一部分的功能是在不创建Bean的情况下获取Bean的类型,防止因为增强器还没有创建,导致对象没有被成功代理
                    Class<?> beanType = this.beanFactory.getType(beanName);
                    if (beanType == null) {
                        continue;
                    }
                    // 如果当前循环的Bean是一个切面类(含有@Aspect注解并且属性名中没有ajc$)
                    if (this.advisorFactory.isAspect(beanType)) {
                        aspectNames.add(beanName);
                        // 包装@Aspect注解的元数据
                        AspectMetadata amd = new AspectMetadata(beanType, beanName);
                        // 默认使用单实例创建切面类
                        if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
                            MetadataAwareAspectInstanceFactory factory =
                                    new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
                            // 创建增强器
                            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 {
                            // 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));
                        }
                    }
                }
                this.aspectBeanNames = aspectNames;
                return advisors;
            }
        }
    }

    // 如果aspectNames不为null,证明之前已经创建过了,直接读缓存即可
    if (aspectNames.isEmpty()) {
        return Collections.emptyList();
    }
    List<Advisor> advisors = new ArrayList<>();
    for (String aspectName : aspectNames) {
        List<Advisor> 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;
}
复制代码

advisorFactory.getAdvisors:缓存Bean中的所有增强器

public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
   // 目标Aspect类
   Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
   // 代理对象Bean的name
   String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
   // 校验Aspect类上是不是标注了@Aspect注解
   validate(aspectClass);

   // We need to wrap the MetadataAwareAspectInstanceFactory with a decorator
   // so that it will only instantiate once.
   MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
         new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);

   List<Advisor> advisors = new ArrayList<>();
   //获取排除@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).
      //真正创建增强器
      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.
   // 通过在装饰者内部的开始加入SyntheticInstantiationAdvisor增强器,达到延迟初始化切面bean的目的
   if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
      Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
      advisors.add(0, instantiationAdvisor);
   }

   // Find introduction fields.
   // 对@DeclareParent注解功能的支持(引入)
   for (Field field : aspectClass.getDeclaredFields()) {
      Advisor advisor = getDeclareParentsAdvisor(field);
      if (advisor != null) {
         advisors.add(advisor);
      }
   }

   return advisors;
}
复制代码

getAdvisor:

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

   validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());
   //解析切入点
   AspectJExpressionPointcut expressionPointcut = getPointcut(
         candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
   if (expressionPointcut == null) {
      return null;
   }
   //将切入点和通知包装成一个切面
   return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
         this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
}
复制代码

getPointcut:解析切入点

private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class<?> candidateAspectClass) {
   //获取切入点的注解通知类型
   AspectJAnnotation<?> aspectJAnnotation =
         AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
   if (aspectJAnnotation == null) {
      return null;
   }

   AspectJExpressionPointcut ajexp =
         new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class<?>[0]);
   ajexp.setExpression(aspectJAnnotation.getPointcutExpression());
   if (this.beanFactory != null) {
      ajexp.setBeanFactory(this.beanFactory);
   }
   return ajexp;
}
复制代码

获取切入点的注解通知类型:@Around、@Before、@After、@AfterReturning、@AfterThrowing(遍历方法时@Pointcut已经被排除了)

protected static AspectJAnnotation<?> findAspectJAnnotationOnMethod(Method method) {
   for (Class<?> clazz : ASPECTJ_ANNOTATION_CLASSES) {
      AspectJAnnotation<?> foundAnnotation = findAnnotation(method, (Class<Annotation>) clazz);
      if (foundAnnotation != null) {
         return foundAnnotation;
      }
   }
   return null;
}
复制代码

2.1.2.2 判断目标对象是不是原始对象(没有代理)

AbstractAutoProxyCreator#shouldSkip

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

.ORIGINAL是Spring框架约定的原始实例,我们写一个类,类名xx.xx.xx.ORIGINAL,那么在实例化这个类时就以强制返回给定的实例,即没有代理。

static boolean isOriginalInstance(String beanName, Class<?> beanClass) {
   if (!StringUtils.hasLength(beanName) || beanName.length() !=
         beanClass.getName().length() + AutowireCapableBeanFactory.ORIGINAL_INSTANCE_SUFFIX.length()) {
      return false;
   }
   return (beanName.startsWith(beanClass.getName()) &&
         beanName.endsWith(AutowireCapableBeanFactory.ORIGINAL_INSTANCE_SUFFIX));
}
复制代码

2.1.3 自定义目标资源,对于单实例Bean必定会返回null

这里会创建自定义目标资源

protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
   // We can't create fancy target sources for directly registered singletons.
   if (this.customTargetSourceCreators != null &&
         this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
      for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
         TargetSource ts = tsc.getTargetSource(beanClass, beanName);
         if (ts != null) {
            // Found a matching TargetSource.
            if (logger.isTraceEnabled()) {
               logger.trace("TargetSourceCreator [" + tsc +
                     "] found custom TargetSource for bean with name '" + beanName + "'");
            }
            return ts;
         }
      }
   }

   // No custom TargetSource found.
   return null;
}
复制代码

2.2 AbstractAutoProxyCreator#postProcessAfterInitialization 实例化之后处理Bean定义信息

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
   if (bean != null) {
      Object cacheKey = getCacheKey(bean.getClass(), beanName);
      //判断Bean是否已经提前创建早期代理引用
      if (this.earlyProxyReferences.remove(cacheKey) != bean) {
         return wrapIfNecessary(bean, beanName, cacheKey);
      }
   }
   return bean;
}
复制代码

判断是否应该创建代理

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
   if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
      return bean;
   }
   if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
      return bean;
   }
   //如果是切面或者原始类就跳过 详细说明:2.1.1和2.1.1.2
   if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
      this.advisedBeans.put(cacheKey, Boolean.FALSE);
      return bean;
   }

   // Create proxy if we have advice.
   //2.2.1 获取增强器
   Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
   if (specificInterceptors != DO_NOT_PROXY) {
      this.advisedBeans.put(cacheKey, Boolean.TRUE);
      //2.2.2 创建代理对象
      Object proxy = createProxy(
            bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
      this.proxyTypes.put(cacheKey, proxy.getClass());
      return proxy;
   }

   this.advisedBeans.put(cacheKey, Boolean.FALSE);
   return bean;
}
复制代码

2.2.1 获取增强器

protected Object[] getAdvicesAndAdvisorsForBean(
      Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
   //获取所有增强器
   List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
   if (advisors.isEmpty()) {
      return DO_NOT_PROXY;
   }
   return advisors.toArray();
}
复制代码
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
   //获取增强器 详细:2.1.2.1 
   List<Advisor> candidateAdvisors = findCandidateAdvisors();
   // 2.2.1.1 获取当前Bean的切面
   List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
   // 2.2.1.2 新增额外的增强器
   extendAdvisors(eligibleAdvisors);
   if (!eligibleAdvisors.isEmpty()) {
      eligibleAdvisors = sortAdvisors(eligibleAdvisors);
   }
   return eligibleAdvisors;
}
复制代码

2.2.1.1 获取当前Bean的切面

解析切入点表达式

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

   ProxyCreationContext.setCurrentProxiedBeanName(beanName);
   try {
      //根据切入点表达式找出当前Bean的增强器
      return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
   }
   finally {
      ProxyCreationContext.setCurrentProxiedBeanName(null);
   }
}
复制代码

2.2.1.2 AspectJAwareAdvisorAutoProxyCreator#extendAdvisors 新增额外的增强器

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

如果Bean有增强器则额外新增一个ExposeInvocationInterceptor增强器放在第一个

public static boolean makeAdvisorChainAspectJCapableIfNecessary(List<Advisor> 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;
         }
      }
      //新增ExposeInvocationInterceptor放在首位
      if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {
         advisors.add(0, ExposeInvocationInterceptor.ADVISOR);
         return true;
      }
   }
   return false;
}
复制代码

AspectJAwareAdvisorAutoProxyCreator实现了MethodInterceptor(方法拦截器)invoke方法,将调用方法放入静态常量ThreadLocal中。

主要作用:在后续的任何下调用链环节,只要需要用到当前的MethodInvocation就通过ExposeInvocationInterceptor.currentInvocation()静态方法获得。

private static final ThreadLocal<MethodInvocation> invocation =
			new NamedThreadLocal<>("Current AOP method invocation");

public Object invoke(MethodInvocation mi) throws Throwable {
   MethodInvocation oldInvocation = invocation.get();
   //将拦截的方法放入ThreadLocal中
   invocation.set(mi);
   try {
      return mi.proceed();
   }
   finally {
      invocation.set(oldInvocation);
   }
}
复制代码

获取调用方法

public static MethodInvocation currentInvocation() throws IllegalStateException {
   MethodInvocation mi = invocation.get();
   if (mi == null) {
      throw new IllegalStateException(
            "No MethodInvocation found: Check that an AOP invocation is in progress and that the " +
            "ExposeInvocationInterceptor is upfront in the interceptor chain. Specifically, note that " +
            "advices with order HIGHEST_PRECEDENCE will execute before ExposeInvocationInterceptor! " +
            "In addition, ExposeInvocationInterceptor and ExposeInvocationInterceptor.currentInvocation() " +
            "must be invoked from the same thread.");
   }
   return mi;
}
复制代码

2.2.2 创建代理对象

protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
      @Nullable Object[] specificInterceptors, TargetSource targetSource) {

   if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
      AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
   }
   // 创建代理工厂,使用它来创建代理对象
   ProxyFactory proxyFactory = new ProxyFactory();
   // 从当前执行的AbstractAutoProxyCreator中复制一些配置
   proxyFactory.copyFrom(this);

   if (!proxyFactory.isProxyTargetClass()) {
      if (shouldProxyTargetClass(beanClass, beanName)) {
         proxyFactory.setProxyTargetClass(true);
      }
      else {
         evaluateProxyInterfaces(beanClass, proxyFactory);
      }
   }
   // 2.2.2.1 组合所有增强器
   Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
   proxyFactory.addAdvisors(advisors);
   proxyFactory.setTargetSource(targetSource);
   customizeProxyFactory(proxyFactory);

   proxyFactory.setFrozen(this.freezeProxy);
   if (advisorsPreFiltered()) {
      proxyFactory.setPreFiltered(true);
   }
   // 2.2.2.2 创建代理对象
   return proxyFactory.getProxy(getProxyClassLoader());
}
复制代码

2.2.2.1 组合所有增强器

protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
    // Handle prototypes correctly...
    // 解析通用拦截器
    Advisor[] commonInterceptors = resolveInterceptorNames();

    List<Object> allInterceptors = new ArrayList<>();
    if (specificInterceptors != null) {
        // 把传入的增强器放入AOP拦截器列表中
        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");
    }

    //2.2.2.1 包装增强器 转换为真正的Advisor增强器对象
    Advisor[] advisors = new Advisor[allInterceptors.size()];
    for (int i = 0; i < allInterceptors.size(); i++) {
        advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
    }
    return advisors;
}
复制代码

2.2.2.1 包装增强器

public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {
    // 如果要封装的对象本身就是Advisor类型,那无需处理,直接强转返回
    if (adviceObject instanceof Advisor) {
        return (Advisor) adviceObject;
    }
    // 如果传入的对象不是Advisor,也不是Advice,那无法处理,要抛出异常
    if (!(adviceObject instanceof Advice)) {
        throw new UnknownAdviceTypeException(adviceObject);
    }
    Advice advice = (Advice) adviceObject;
    // MethodInterceptor类型的增强器,会使用DefaultPointcutAdvisor包装
    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);
}
复制代码

2.2.2.2 创建代理对象

public Object getProxy(@Nullable ClassLoader classLoader) {
    //2.2.2.2.1 创建AOP代理对象 2.2.2.2.2 获取代理类
    return createAopProxy().getProxy(classLoader);
}
复制代码

2.2.2.2.1 创建AOP代理工厂

protected final synchronized AopProxy createAopProxy() {
   if (!this.active) {
      //回调增强器监听器(AdvisedSupportListener)
      activate();
   }
   //创建代理对象
   return getAopProxyFactory().createAopProxy(this);
}
复制代码

DefaultAopProxyFactory#createAopProxy

如果目标对象有接口,用jdk动态代理 没有接口,用cglib动态代理。

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
   //①是否开启了优化策略(默认为false)|| ②代理类(默认为false 从@EnableAspectJAutoProxy属性中设置的) || ③目标类没有实现接口或者实现接口是SpringProxy
   if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
      Class<?> targetClass = config.getTargetClass();
      if (targetClass == null) {
         throw new AopConfigException("TargetSource cannot determine target class: " +
               "Either an interface or a target is required for proxy creation.");
      }
      //目标类是一个接口或者是代理类
      if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
         return new JdkDynamicAopProxy(config);
      }
      return new ObjenesisCglibAopProxy(config);
   }
   else {
      return new JdkDynamicAopProxy(config);
   }
}
复制代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值