SpringBoot集成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);
         }
      }
   }
}

流程如下图:

Spring源码解析之Aop切面和代理对象的创建

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源码解析之Aop切面和代理对象的创建

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);
   }
}
2.2.2.2.2 获取署理类