SpringAOP源码阅读-AnnotationAwareAspectJAutoProxyCreator

在《SpringAOP源码阅读-@EnableAspectJAutoProxy》存在笔误,最终注册的是这个AnnotationAwareAspectJAutoProxyCreator

兄弟们,今天我们来看一下,我们的Bean对象如何被创建代理对象的。完成这一操作的类就是AnnotationAwareAspectJAutoProxyCreatorSpringAOP源码阅读-AnnotationAwareAspectJAutoProxyCreator

基础接口介绍

BeanPostProcessor

public interface BeanPostProcessor {

 @Nullable
 default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  return bean;
 }

 @Nullable
 default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  return bean;
 }

}

  • postProcessBeforeInitialization:初始化方法执行前
  • postProcessAfterInitialization:初始化方法执行后

InstantiationAwareBeanPostProcessor

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {

 @Nullable
 default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
  return null;
 }

 default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
  return true;
 }

 @Nullable
 default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
   throws BeansException 
{

  return null;
 }


 @Deprecated
 @Nullable
 default PropertyValues postProcessPropertyValues(
   PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
 throws BeansException 
{

  return pvs;
 }

}
  • postProcessBeforeInstantiation:在实例化前执行
  • postProcessAfterInstantiation:在实例化后填充属性前执行
  • postProcessProperties:填充属性阶段执行

这里我把AnnotationAwareAspectJAutoProxyCreator实现的接口所拥有的方法以及执行时机列举,后面直接去分析AnnotationAwareAspectJAutoProxyCreator这几个方法的实现

Bean创建的各个时期

postProcessBeforeInstantiation

实例化前阶段

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
implements SmartInstantiationAwareBeanPostProcessorBeanFactoryAware 
{
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
        Object cacheKey = getCacheKey(beanClass, beanName);

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

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

        return null;
    }
}

按源码注释上说,如果创建的Bean有自定义的TargetSource在这一阶段就创建代理并返回。 对于我们正常写的Bean,这段代码什么也没做

postProcessAfterInstantiation

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {

 default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
  return true;
 }
}

没有重写,直接返回true

postProcessProperties

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
 @Nullable
 default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
   throws BeansException 
{

  return null;
 }
}

没有重写

postProcessBeforeInitialization

public interface BeanPostProcessor {
 @Nullable
 default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  return bean;
 }
}

太棒了,AnnotationAwareAspectJAutoProxyCreator又没做实现

postProcessAfterInitialization

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
  implements SmartInstantiationAwareBeanPostProcessorBeanFactoryAware 
{
 /**
  * @see #getAdvicesAndAdvisorsForBean
  */

 @Override
 public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
  if (bean != null) {
   Object cacheKey = getCacheKey(bean.getClass(), beanName);
   if (this.earlyProxyReferences.remove(cacheKey) != bean) {
    return wrapIfNecessary(bean, beanName, cacheKey);
   }
  }
  return bean;
 }
}

这个方法中我们记住两个东西

  • earlyProxyReferences
  • wrapIfNecessary

下面我们看下wrapIfNecessary方法实现

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;
    }
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

    // Create proxy if we have advice.
    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;
}
  1. 先是一波判断,校验bean是否已经被代理之类的
  2. 进入getAdvicesAndAdvisorsForBean寻找AdviceAdvisor
  3. 进行代理的创建

getAdvicesAndAdvisorsForBean

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

继续进入findEligibleAdvisors

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;
}
  1. 寻找所有候选的Advisor
  2. 筛选出可用

寻找所有Advisor

进入findCandidateAdvisors()

@SuppressWarnings("serial")
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {

 @Nullable
 private List<Pattern> includePatterns;

 @Nullable
 private AspectJAdvisorFactory aspectJAdvisorFactory;

 @Nullable
 private BeanFactoryAspectJAdvisorsBuilder aspectJAdvisorsBuilder;

 @Override
 protected List<Advisor> findCandidateAdvisors() {
  // Add all the Spring advisors found according to superclass rules.
  List<Advisor> advisors = super.findCandidateAdvisors();
  // Build Advisors for all AspectJ aspects in the bean factory.
  if (this.aspectJAdvisorsBuilder != null) {
   advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
  }
  return advisors;
 }
}

这里super.findCandidateAdvisors()就不进入了 我们进入aspectJAdvisorsBuilder.buildAspectJAdvisors()

public class BeanFactoryAspectJAdvisorsBuilder {

 private final ListableBeanFactory beanFactory;

 private final AspectJAdvisorFactory advisorFactory;

 @Nullable
 private volatile List<String> aspectBeanNames;

 private final Map<String, List<Advisor>> advisorsCache = new ConcurrentHashMap<>();

 private final Map<String, MetadataAwareAspectInstanceFactory> aspectFactoryCache = new ConcurrentHashMap<>();


 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<>();
     String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
       this.beanFactory, Object.classtruefalse);
     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.
      Class<?> beanType = this.beanFactory.getType(beanName, false);
      if (beanType == null) {
       continue;
      }
      if (this.advisorFactory.isAspect(beanType)) {
       aspectNames.add(beanName);
       AspectMetadata amd = new AspectMetadata(beanType, beanName);
       if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
        MetadataAwareAspectInstanceFactory factory =
          new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
        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 {
           //..........
       }
      }
     }
     this.aspectBeanNames = aspectNames;
     return advisors;
    }
   }
  }

     //......
  return advisors;
 }



}

就是这段代码,可以为我找到所有的@Aspect切面

  1. 它会获取所有的beanName
  2. 如果bean上被标注了@Aspect则继续下面操作
  3. aspectNames加入这个beanName
  4. @Aspect标注的Bean也分单例和不是单例,我们只看单例的
  5. @Aspect标注的Bean最终被解析成List<Advisor> classAdvisors一个Advisor列表,用到的类是AspectJAdvisorFactory

筛选可用的Advisor

进入findAdvisorsThatCanApply()

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

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

废话不多说直接进入AopUtils.findAdvisorsThatCanApply

 public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
  if (candidateAdvisors.isEmpty()) {
   return candidateAdvisors;
  }
  List<Advisor> eligibleAdvisors = new ArrayList<>();
  for (Advisor candidate : candidateAdvisors) {
   if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
    eligibleAdvisors.add(candidate);
   }
  }
  boolean hasIntroductions = !eligibleAdvisors.isEmpty();
  for (Advisor candidate : candidateAdvisors) {
   if (candidate instanceof IntroductionAdvisor) {
    // already processed
    continue;
   }
   if (canApply(candidate, clazz, hasIntroductions)) {
    eligibleAdvisors.add(candidate);
   }
  }
  return eligibleAdvisors;
 }

直接看canApply

 public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
  if (advisor instanceof IntroductionAdvisor) {
   return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
  }
  else if (advisor instanceof PointcutAdvisor) {
   PointcutAdvisor pca = (PointcutAdvisor) advisor;
   return canApply(pca.getPointcut(), targetClass, hasIntroductions);
  }
  else {
   // It doesn't have a pointcut so we assume it applies.
   return true;
  }
 }

我们看PointcutAdvisor情况下的canApply

public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
  Assert.notNull(pc, "Pointcut must not be null");
  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)) {
   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;
 }

舒服了,通过PointCut中的MethodMatcherClassFilter判断目标类是否可以被应用

代理创建

 protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
   @Nullable Object[] specificInterceptors, TargetSource targetSource)
 
{
  ProxyFactory proxyFactory = new ProxyFactory();
  Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
  proxyFactory.addAdvisors(advisors);
  proxyFactory.setTargetSource(targetSource);
        ClassLoader classLoader = getProxyClassLoader();
  return proxyFactory.getProxy(classLoader);
 }

创建代理的方法我砍调了好多细节后,是不是就是我们手动new ProxyFactory()然后创建代理的方式,简直是一模一样

·proxyFactory.getProxy再往下探,发现它用的是DefaultAopProxyFactory,其创建Aop代理的方法

 @Override
 public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
  if (!NativeDetector.inNativeImage() &&
    (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) || ClassUtils.isLambdaClass(targetClass)) {
    return new JdkDynamicAopProxy(config);
   }
   return new ObjenesisCglibAopProxy(config);
  }
  else {
   return new JdkDynamicAopProxy(config);
  }
 }

看到没有,

  • ObjenesisCglibAopProxy
  • JdkDynamicAopProxy

总结

一般情况下,Aop代理的创建就是在初始化阶段执行BeanPostProcessor#postProcessAfterInitialization时,为该bean获取所有匹配的Advisor,然后为其生成Aop代理。生成代理的方式有Cglib和Jdk动态代理两种方式。


原文始发于微信公众号(溪溪技术笔记):SpringAOP源码阅读-AnnotationAwareAspectJAutoProxyCreator

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/207141.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!