动态AOP-Spring AOP 基于@AspectJ

狂风中的少年 提交于 2020-02-26 14:22:26

XML配置 aspectj-autoproxy

注册自定义命名空间Bean定义解析器 AopNamespaceHandler

public class AopNamespaceHandler extends NamespaceHandlerSupport {

public void init() {

 // In 2.0 XSD as well as in 2.1 XSD.

 registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());

 registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());

 registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());

 

 // Only in 2.0 XSD: moved to context namespace as of 2.1

 registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());

}

}

 

AspectJAutoProxyBeanDefinitionParser

public BeanDefinition parse(Element element, ParserContext parserContext) {

 AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);

 extendBeanDefinition(element, parserContext);

 return null;

}

 

private void extendBeanDefinition(Element element, ParserContext parserContext) {

 BeanDefinition beanDef =

   parserContext.getRegistry().getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);

 if (element.hasChildNodes()) {

  addIncludePatterns(element, parserContext, beanDef);

 }

}

 

private void addIncludePatterns(Element element, ParserContext parserContext, BeanDefinition beanDef) {

 ManagedList<TypedStringValue> includePatterns = new ManagedList<>();

 NodeList childNodes = element.getChildNodes();

 for (int i = 0; i < childNodes.getLength(); i++) {

  Node node = childNodes.item(i);

  if (node instanceof Element) {

   Element includeElement = (Element) node;

   TypedStringValue valueHolder = new TypedStringValue(includeElement.getAttribute("name"));

   valueHolder.setSource(parserContext.extractSource(includeElement));

   includePatterns.add(valueHolder);

  }

 }

 if (!includePatterns.isEmpty()) {

  includePatterns.setSource(parserContext.extractSource(element));

  beanDef.getPropertyValues().add("includePatterns", includePatterns);

 }

}

 

注册AnnotationAwareAspectJAutoProxyCreator

AopNamespaceUtils

public static final String AUTO_PROXY_CREATOR_BEAN_NAME =

  "org.springframework.aop.config.internalAutoProxyCreator";

注册名称为AUTO_PROXY_CREATOR_BEAN_NAME的BeanBeanDefinition。

public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(

  ParserContext parserContext, Element sourceElement) {

 

 BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(

   parserContext.getRegistry(), parserContext.extractSource(sourceElement));

 useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);

 registerComponentIfNecessary(beanDefinition, parserContext);

}

 

基于@AspectJ代理创建流程

(1) 如果存在循环依赖,调用getEarlyBeanReference方法获取提前暴露的Bean,如果有必要会生成代理,并记录下未包装的Bean

(2) Bean实例化前调用postProcessBeforeInstantiation,如果有自定义的TargetSourceCreator,则会创建代理

(3) Bean实例化后调用postProcessAfterInitialization,如果没有循环依赖或者循环依赖后Bean改变了,则需要生成代理

 

1、AnnotationAwareAspectJAutoProxyCreator类图

image.png

 

1.1 Aop基础设施标记接口-AopInfrastructureBean

标记接口,指示作为Spring AOP基础设施一部分的bean。 特别是,这意味着即使切入点匹配,任何此类bean也不会进行自动代理。

 

1.2 覆写查找候选Advisor findCandidateAdvisors

protected List<Advisor> findCandidateAdvisors() {

 // 调用父类获取所有配置的Advisor

 List<Advisor> advisors = super.findCandidateAdvisors();

 // BeanFactory中所有AspectJ的Advisor

 if (this.aspectJAdvisorsBuilder != null) {

  advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());

 }

 return advisors;

}

 

1.3 覆写判断是否基础设置类 isInfrastructureClass

protected boolean isInfrastructureClass(Class<?> beanClass) {

 return (super.isInfrastructureClass(beanClass) ||

   (this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));

}

 

1.4 覆写判断是否合适Aspect Bean isEligibleAspectBean

// includePatterns指定哪些Aspect Bean符合。检查给定的Aspect bean是否符合自动代理的条件。如果未使用任何<aop:include>元素,则“ includePatterns”将为{@code null},并且包括所有bean。如果“ includePatterns”非空,则模式之一必须匹配。

protected boolean isEligibleAspectBean(String beanName) {

 if (this.includePatterns == null) {

  return true;

 }

 else {

  for (Pattern pattern : this.includePatterns) {

   if (pattern.matcher(beanName).matches()) {

    return true;

   }

  }

  return false;

 }

}

 

1.5 根据@Aspect构造Advisor提取AspectJ Advisor 

1.5.1 BeanFactoryAspectJAdvisorsBuilderAdapter

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

 }

}

 

1.5.2 根据@Aspect构造Advisor BeanFactoryAspectJAdvisorsBuilder

// 根据@Aspect构造Advisor

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

    // 获取所有注册Bean名称

    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(

      this.beanFactory, Object.class, true, false);

    for (String beanName : beanNames) {

     // 如果不是匹配的Aspect Bean忽略不处理

     if (!isEligibleBean(beanName)) {

      continue;

     }

     // 我们必须小心,不要急于实例化bean,因为在这种情况下,它们将被spring容器缓存,但不会被编织。

     Class<?> beanType = this.beanFactory.getType(beanName);

     if (beanType == null) {

      continue;

     }

// 是否有@Aspect注解以且未被织入即属性名称不是以ajc$开头

     if (this.advisorFactory.isAspect(beanType)) {

      aspectNames.add(beanName);

      AspectMetadata amd = new AspectMetadata(beanType, beanName);

 // Aspect实例化模型是单例

      if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {

       MetadataAwareAspectInstanceFactory factory =

         new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);

       // 获取@Aspect注解类中定义的Advisor,ReflectiveAspectJAdvisorFactory

       List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);

       if (this.beanFactory.isSingleton(beanName)) {

   // 名称为beanName的Bean是单例,且Aspect实例化模型是单例,Advisor缓存起来

        this.advisorsCache.put(beanName, classAdvisors);

       }

       else {

        // 名称为beanName的Bean不是单例,但Aspect实例化模型是单例,工厂缓存起来

        this.aspectFactoryCache.put(beanName, factory);

       }

       advisors.addAll(classAdvisors);

      }

      else {

       // 名称为beanName的Bean是单例,但Aspect实例化模型不是单例,抛异常

       if (this.beanFactory.isSingleton(beanName)) {

        throw new IllegalArgumentException("Bean with name '" + beanName +

          "' is a singleton, but aspect instantiation model is not singleton");

       }

       // 名称为beanName的Bean不是单例,且Aspect实例化模型不是单例,工厂缓存起来

       MetadataAwareAspectInstanceFactory factory =

         new PrototypeAspectInstanceFactory(this.beanFactory, beanName);

       this.aspectFactoryCache.put(beanName, factory);

       advisors.addAll(this.advisorFactory.getAdvisors(factory));

      }

     }

    }

    this.aspectBeanNames = aspectNames;

    return advisors;

   }

  }

 }

 

 if (aspectNames.isEmpty()) {

  return Collections.emptyList();

 }

 List<Advisor> advisors = new ArrayList<>();

 for (String aspectName : aspectNames) {

  // Aspect实例化模型是单例,且名称为beanName的Bean是单例

  List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);

  if (cachedAdvisors != null) {

   advisors.addAll(cachedAdvisors);

  }

  else {

   // Aspect实例化模型不是单例且名称为beanName的Bean不是单例,或者Aspect实例化模型是单例,但名称为beanName的Bean不是单例

   MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);

   advisors.addAll(this.advisorFactory.getAdvisors(factory));

  }

 }

 return advisors;

}

 

2、AspectJAwareAdvisorAutoProxyCreator

覆写了父类AbstractAdvisorAutoProxyCreator的sortAdvisors、extendAdvisors、shouldSkip方法。

2.1 Advisor排序sortAdvisors

protected List<Advisor> sortAdvisors(List<Advisor> advisors) {

 List<PartiallyComparableAdvisorHolder> partiallyComparableAdvisors = new ArrayList<>(advisors.size());

 for (Advisor element : advisors) {

  partiallyComparableAdvisors.add(

    new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR));

 }

 List<PartiallyComparableAdvisorHolder> sorted = PartialOrder.sort(partiallyComparableAdvisors);

 if (sorted != null) {

  List<Advisor> result = new ArrayList<>(advisors.size());

  for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) {

   result.add(pcAdvisor.getAdvisor());

  }

  return result;

 }

 else {

  return super.sortAdvisors(advisors);

 }

}

 

2.2 extendAdvisors

// 获取到使用指定Bean的Advisor后进行扩展

protected void extendAdvisors(List<Advisor> candidateAdvisors) {

 // 如果是AspectJ advice则会额外添加ExposeInvocationInterceptor.ADVISOR

 AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);

}

 

2.2.1 AspectJProxyUtils

// 添加ExposeInvocationInterceptor.ADVISOR

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) {

   if (isAspectJAdvice(advisor)) {

    foundAspectJAdvice = true;

    break;

   }

  }

  if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {

   advisors.add(0, ExposeInvocationInterceptor.ADVISOR);

   return true;

  }

 }

 return false;

}

 

// 确定给定的Advisor是否包含AspectJ advice

private static boolean isAspectJAdvice(Advisor advisor) {

 return (advisor instanceof InstantiationModelAwarePointcutAdvisor ||

   advisor.getAdvice() instanceof AbstractAspectJAdvice ||

   (advisor instanceof PointcutAdvisor &&

     ((PointcutAdvisor) advisor).getPointcut() instanceof AspectJExpressionPointcut));

}

 

2.3 shouldSkip

// 如果是AspectJPointcutAdvisor实例且Bean名称和AspectName相同则忽略

protected boolean shouldSkip(Class<?> beanClass, String beanName) {

 List<Advisor> candidateAdvisors = findCandidateAdvisors();

 for (Advisor advisor : candidateAdvisors) {

  if (advisor instanceof AspectJPointcutAdvisor &&

    ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {

   return true;

  }

 }

 return super.shouldSkip(beanClass, beanName);

}

 

3、AbstractAdvisorAutoProxyCreator

3.1 isEligibleAdvisorBean

// 给定名称的Advisor Bean是否是合格的Advisor。

protected boolean isEligibleAdvisorBean(String beanName) {

 return true;

}

 

3.2 自定义BeanFactoryAdvisorRetrievalHelper提取Advisor

private class BeanFactoryAdvisorRetrievalHelperAdapter extends BeanFactoryAdvisorRetrievalHelper {

 public BeanFactoryAdvisorRetrievalHelperAdapter(ConfigurableListableBeanFactory beanFactory) {

  super(beanFactory);

 }

 

 @Override

 protected boolean isEligibleBean(String beanName) {

  return AbstractAdvisorAutoProxyCreator.this.isEligibleAdvisorBean(beanName);

 }

}

 

3.3 获取AdvicesAndAdvisors

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

}

 

// 查找所有合格的Advisor,自动代理使用

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

 List<Advisor> candidateAdvisors = findCandidateAdvisors();

 List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);

 // 留给子类扩展

 extendAdvisors(eligibleAdvisors);

 if (!eligibleAdvisors.isEmpty()) {

  // 留给子类扩展排序

  eligibleAdvisors = sortAdvisors(eligibleAdvisors);

 }

 return eligibleAdvisors;

}

 

// 查找要在自动代理中使用的所有候选Advisor

protected List<Advisor> findCandidateAdvisors() {

 Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");

 return this.advisorRetrievalHelper.findAdvisorBeans();

}

 

// 搜索给定的候选Advisor,以查找可以应用于指定bean的所有Advisor

protected List<Advisor> findAdvisorsThatCanApply(

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

 ProxyCreationContext.setCurrentProxiedBeanName(beanName);

 try {

  return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);

 }

 finally {

  ProxyCreationContext.setCurrentProxiedBeanName(null);

 }

}

 

4、AbstractAutoProxyCreator

AbstractAutoProxyCreator实现了SmartInstantiationAwareBeanPostProcessor。

 

4.1 Bean实例化前创建代理实例 postProcessBeforeInstantiation

public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {

 Object cacheKey = getCacheKey(beanClass, beanName);

 

 // beanName为空或者targetSourcedBeans不包含beanName

 if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {

  // Bean已经增强

  if (this.advisedBeans.containsKey(cacheKey)) {

   return null;

  }

 

  // 基础设施类或者需要忽略的类

  if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {

   this.advisedBeans.put(cacheKey, Boolean.FALSE);

   return null;

  }

 }

 

// 如果我们有自定义的TargetSource,请在此处创建代理。禁止目标Bean的不必要的默认实例化:TargetSource将以自定义方式处理目标实例。

 TargetSource targetSource = getCustomTargetSource(beanClass, beanName);

 if (targetSource != null) {

  if (StringUtils.hasLength(beanName)) {

   this.targetSourcedBeans.add(beanName);

  }

 

  // 获取适用于Bean的Advisor

  Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);

  // 创建代理

  Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);

  // 缓存代理类型

  this.proxyTypes.put(cacheKey, proxy.getClass());

  return proxy;

 }

 

 return null;

}

 

4.2 Bean初始化后进行包装 postProcessAfterInitialization

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {

 if (bean != null) {

  Object cacheKey = getCacheKey(bean.getClass(), beanName);

  // 没有循环依赖或者有循环依赖且被其它BeanPostProcessor代理了

  if (this.earlyProxyReferences.remove(cacheKey) != bean) {

   return wrapIfNecessary(bean, beanName, cacheKey);

  }

 }

 return bean;

}

 

4.3 获取提早暴露的Bean getEarlyBeanReference

public Object getEarlyBeanReference(Object bean, String beanName) {

 Object cacheKey = getCacheKey(bean.getClass(), beanName);

 // 循环依赖记录下包装前的Bean

 this.earlyProxyReferences.put(cacheKey, bean);

 return wrapIfNecessary(bean, beanName, cacheKey);

}

 

4.4 包装Bean wrapIfNecessary

// 必要时包装给定的bean,即是否有资格被代理。

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {

  // 当前已经生成代理对象,不用再次创建代理

 if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {

  return bean;

 }

 

 // 忽略的或者没有适用Advisor的Bean

 if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {

  return bean;

 }

 

 // 基础设施类或者需要忽略的类

 if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {

  this.advisedBeans.put(cacheKey, Boolean.FALSE);

  return bean;

 }

 

 // 获取适用于Bean的Advisor

 Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);

 if (specificInterceptors != DO_NOT_PROXY) {

  this.advisedBeans.put(cacheKey, Boolean.TRUE);

  // 创建代理

  Object proxy = createProxy(

    bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));

  // 缓存代理类型

  this.proxyTypes.put(cacheKey, proxy.getClass());

  return proxy;

 }

 

 this.advisedBeans.put(cacheKey, Boolean.FALSE);

 return bean;

}

 

4.5  创建代理实例 createProxy

protected Object createProxy(Class<?> beanClass, @Nullable String beanName,

  @Nullable Object[] specificInterceptors, TargetSource targetSource) {

 

 if (this.beanFactory instanceof ConfigurableListableBeanFactory) {

   // 公开指定bean的targetClass,BeanDefinition添加属性

  AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);

 }

 

 ProxyFactory proxyFactory = new ProxyFactory();

 proxyFactory.copyFrom(this);

 

 if (!proxyFactory.isProxyTargetClass()) {

 // 确定给定的bean是否应使用其目标类而不是其接口进行代理。检查相应bean定义的 {@link PRESERVE_TARGET_CLASS_ATTRIBUTE“ preserveTargetClass”属性} 。

  if (shouldProxyTargetClass(beanClass, beanName)) {

   proxyFactory.setProxyTargetClass(true);

  }

  else {

   // 检查给定bean类上的接口,是否基于接口代理。

   evaluateProxyInterfaces(beanClass, proxyFactory);

  }

 }

 

 // 构造Advisor

 Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);

 proxyFactory.addAdvisors(advisors);

 proxyFactory.setTargetSource(targetSource);

 customizeProxyFactory(proxyFactory);

 

 proxyFactory.setFrozen(this.freezeProxy);

 if (advisorsPreFiltered()) {

  proxyFactory.setPreFiltered(true);

 }

 

 return proxyFactory.getProxy(getProxyClassLoader());

}

 

4.6 构造Advisor buildAdvisors

// 确定给定bean的Advisor,包括适用于Advisor接口的特定拦截器和公共拦截器。

protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {

 // 配置的拦截器包装成Advisor

 Advisor[] commonInterceptors = resolveInterceptorNames();

 

 List<Object> 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++) {

  // 拦截器包装,将不是Advisor的包装成Advisor

  advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));

 }

 return advisors;

}

 

4.7 拦截器解析为Advisor resolveInterceptorNames

private Advisor[] resolveInterceptorNames() {

 BeanFactory bf = this.beanFactory;

 ConfigurableBeanFactory cbf = (bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null);

 List<Advisor> advisors = new ArrayList<>();

 for (String beanName : this.interceptorNames) {

  // 配置的拦截器没有在创建中,包装成Advisor

  if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {

   Assert.state(bf != null, "BeanFactory required for resolving interceptor names");

   Object next = bf.getBean(beanName);

   advisors.add(this.advisorAdapterRegistry.wrap(next));

  }

 }

 return advisors.toArray(new Advisor[0]);

}

 

4.8 判断是否基础设置类 isInfrastructureClass

protected boolean isInfrastructureClass(Class<?> beanClass) {

 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;

}

 

4.9 判断是否跳过 shouldSkip

protected boolean shouldSkip(Class<?> beanClass, String beanName) {

 return AutoProxyUtils.isOriginalInstance(beanName, beanClass);

}

 

5、通用功能基类 ProxyProcessorSupport

具有代理处理器通用功能的基类,尤其是ClassLoader管理和{@link #evaluateProxyInterfaces}算法。

 

// 检查给定bean类上的接口,并在适当时将它们应用于{@link ProxyFactory}。调用{@link #isConfigurationCallbackInterface}和{@link #isInternalLanguageInterface}筛选合理的代理接口,否则返回目标类代理。

protected void evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory) {

 Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, getProxyClassLoader());

 boolean hasReasonableProxyInterface = false;

 for (Class<?> ifc : targetInterfaces) {

  if (!isConfigurationCallbackInterface(ifc) && !isInternalLanguageInterface(ifc) &&

    ifc.getMethods().length > 0) {

   hasReasonableProxyInterface = true;

   break;

  }

 }

 if (hasReasonableProxyInterface) {

  // Must allow for introductions; can't just set interfaces to the target's interfaces only.

  for (Class<?> ifc : targetInterfaces) {

   proxyFactory.addInterface(ifc);

  }

 }

 else {

  proxyFactory.setProxyTargetClass(true);

 }

}

 

// 确定给定的接口是否只是Spring容器定义的接口,因此不被视为合理的代理接口。如果没有为给定的bean找到合理的代理接口,则将其完整的目标类作为代理,假设这是用户的意图。

protected boolean isConfigurationCallbackInterface(Class<?> ifc) {

 return (InitializingBean.class == ifc || DisposableBean.class == ifc || Closeable.class == ifc ||

   AutoCloseable.class == ifc || ObjectUtils.containsElement(ifc.getInterfaces(), Aware.class));

}

 

// 确定给定的接口是否是众所周知的内部语言接口,因此不被视为合理的代理接口。如果没有为给定的bean找到合理的代理接口,则将其完整的目标类作为代理,假设这是用户的意图。

protected boolean isInternalLanguageInterface(Class<?> ifc) {

 return (ifc.getName().equals("groovy.lang.GroovyObject") ||

   ifc.getName().endsWith(".cglib.proxy.Factory") ||

   ifc.getName().endsWith(".bytebuddy.MockAccess"));

}

 

6、Advisor检索BeanFactoryAdvisorRetrievalHelper

// 在当前bean工厂中查找所有合格的Advisor bean,忽略FactoryBeans并排除当前正在创建的bean。

public List<Advisor> findAdvisorBeans() {

 // 缓存的Advisor Bean名称列表

 String[] advisorNames = this.cachedAdvisorBeanNames;

 if (advisorNames == null) {

  // 获取所有Advisor定义的Bean名称。不要在这里初始化FactoryBean:我们需要保留所有未初始化的常规bean,以使自动代理创建者对其应用!

  advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(

    this.beanFactory, Advisor.class, true, false);

  this.cachedAdvisorBeanNames = advisorNames;

 }

 

 if (advisorNames.length == 0) {

  return new ArrayList<>();

 }

 

 List<Advisor> advisors = new ArrayList<>();

 for (String name : advisorNames) {

  // 判断是否是合格的Advisor

  if (isEligibleBean(name)) {

   // 忽略正在创建中的Advisor

   if (this.beanFactory.isCurrentlyInCreation(name)) {

    if (logger.isTraceEnabled()) {

     logger.trace("Skipping currently created advisor '" + name + "'");

    }

   }

   else {

    try {

     // 获取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;

}

 

7、AOP支持工具类 AopUtils

7.1 查找适用于Bean的Advisor findAdvisorsThatCanApply

// 确定适用于给定类的{@code advisoryAdvisors}列表的子列表。

public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {

 if (candidateAdvisors.isEmpty()) {

  return candidateAdvisors;

 }

 List<Advisor> eligibleAdvisors = new ArrayList<>();

 

 // 找出适用于Bean的IntroductionAdvisor

 for (Advisor candidate : candidateAdvisors) {

  // IntroductionAdvisor是否适用于Bean

  if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {

   eligibleAdvisors.add(candidate);

  }

 }

 

 // 是否有适用于Bean的IntroductionAdvisor

 boolean hasIntroductions = !eligibleAdvisors.isEmpty();

 for (Advisor candidate : candidateAdvisors) {

  // 如果是IntroductionAdvisor忽律,前面已经处理过

  if (candidate instanceof IntroductionAdvisor) {

   continue;

  }

  if (canApply(candidate, clazz, hasIntroductions)) {

   eligibleAdvisors.add(candidate);

  }

 }

 return eligibleAdvisors;

}

 

7.2 检测Advisor是否适用于Bean

public static boolean canApply(Advisor advisor, Class<?> targetClass) {

 return canApply(advisor, targetClass, false);

}

 

public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {

 if (advisor instanceof IntroductionAdvisor) {

  return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);

 }

 else if (advisor instanceof PointcutAdvisor) {

  PointcutAdvisor pca = (PointcutAdvisor) advisor;

  return canApply(pca.getPointcut(), targetClass, hasIntroductions);

 }

 else {

  // 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");

 // Advisor的Pointcut是否匹配目指定类

 if (!pc.getClassFilter().matches(targetClass)) {

  return false;

 }

 

 MethodMatcher methodMatcher = pc.getMethodMatcher();

 // 方法是否动态匹配即根据参数判断

 if (methodMatcher == MethodMatcher.TRUE) {

  return true;

 }

 

 IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;

 if (methodMatcher instanceof IntroductionAwareMethodMatcher) {

  introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;

 }

 

 Set<Class<?>> classes = new LinkedHashSet<>();

 if (!Proxy.isProxyClass(targetClass)) {

  // 返回给定类的用户定义类:通常只是给定类,但对于CGLIB生成的子类,则返回原始类。

  classes.add(ClassUtils.getUserClass(targetClass));

 }

 

 // 获取所有的接口

 classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));

 

 // 所有接口所有方法进行匹配

 for (Class<?> clazz : classes) {

  Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);

  for (Method method : methods) {

   if (introductionAwareMethodMatcher != null ?

     introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :

     methodMatcher.matches(method, targetClass)) {

    return true;

   }

  }

 }

 

 return false;

}

 

8、生成Advisor ReflectiveAspectJAdvisorFactory

8.1 生成getAdvisors

public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {

 Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();

 String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();

 validate(aspectClass);

 

 // 我们需要用装饰器包装MetadataAwareAspectInstanceFactory,使其仅实例化一次。

 MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =

   new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);

 

 List<Advisor> advisors = new ArrayList<>();

 for (Method method : getAdvisorMethods(aspectClass)) {

  Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), 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);

  }

 }

 

 return advisors;

}

 

8.2 获取Aspect类中非@Pointcut标准的方法 getAdvisorMethods

private List<Method> getAdvisorMethods(Class<?> aspectClass) {

 final List<Method> methods = new ArrayList<>();

 ReflectionUtils.doWithMethods(aspectClass, method -> {

  // Exclude pointcuts

  if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {

   methods.add(method);

  }

 });

 methods.sort(METHOD_COMPARATOR);

 return methods;

}

 

8.3 创建Advisor

public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,

  int declarationOrderInAspect, String aspectName) {

 

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

 

 // 获取AspectJ表达式

 AspectJExpressionPointcut expressionPointcut = getPointcut(

   candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());

 if (expressionPointcut == null) {

  return null;

 }

 

 return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,

   this, aspectInstanceFactory, declarationOrderInAspect, aspectName);

}

 

8.4 获取AspectJ表达式

private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class<?> candidateAspectClass) {

 // 查找并返回给定方法的第一个AspectJ注解

 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;

}

 

8.5 根据不同AspectJ注解生成Advice

public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut,

  MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {

 

 Class<?> candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();

 validate(candidateAspectClass);

 

 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

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

 }

 

 AbstractAspectJAdvice springAdvice;

 

 switch (aspectJAnnotation.getAnnotationType()) {

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

 String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);

 if (argNames != null) {

  springAdvice.setArgumentNamesFromStringArray(argNames);

 }

 springAdvice.calculateArgumentBindings();

 

 return springAdvice;

}

 

9 InstantiationModelAwarePointcutAdvisorImpl

public InstantiationModelAwarePointcutAdvisorImpl(AspectJExpressionPointcut declaredPointcut,

  Method aspectJAdviceMethod, AspectJAdvisorFactory aspectJAdvisorFactory,

  MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {

 

 this.declaredPointcut = declaredPointcut;

 this.declaringClass = aspectJAdviceMethod.getDeclaringClass();

 this.methodName = aspectJAdviceMethod.getName();

 this.parameterTypes = aspectJAdviceMethod.getParameterTypes();

 this.aspectJAdviceMethod = aspectJAdviceMethod;

 this.aspectJAdvisorFactory = aspectJAdvisorFactory;

 this.aspectInstanceFactory = aspectInstanceFactory;

 this.declarationOrder = declarationOrder;

 this.aspectName = aspectName;

 

 if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {

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

  this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);

 }

}

 

private Advice instantiateAdvice(AspectJExpressionPointcut pointcut) {

// 调用8.5

 Advice advice = this.aspectJAdvisorFactory.getAdvice(this.aspectJAdviceMethod, pointcut,

   this.aspectInstanceFactory, this.declarationOrder, this.aspectName);

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

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!