美文网首页
5、Spring事务 生成代理

5、Spring事务 生成代理

作者: timar | 来源:发表于2019-10-23 18:13 被阅读0次

上一篇提到了AutoProxyRegistrar向容器中注册了类型为InfrastructureAdvisorAutoProxyCreator的bean


image.png

InfrastructureAdvisorAutoProxyCreator实现了接口BeanPostProcessor,在容器初始化过程中会调用BeanPostProcessor的前置处理postProcessBeforeInitialization(Object bean, String beanName)和后置处理postProcessAfterInitialization(Object bean, String beanName)
生成代理的逻辑就是在后置处理逻辑中,具体实现在AbstractAutoProxyCreator中,AbstractAutoProxyCreator是AOP中一个很重要的类。

看下AbstractAutoProxyCreator的后置处理逻辑

@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
   if (bean != null) {
        // 如果是FactoryBean,用$+beanName作为key,否则直接用beanName
      Object cacheKey = getCacheKey(bean.getClass(), beanName);
        // earlyProxyReferences,包含所有已经生成过代理对象的key
      if (!this.earlyProxyReferences.contains(cacheKey)) {
         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;
   }
    // 如果bean是Advice、Pointcut、Advisor、AopInfrastructureBean中一种或者实现类,
    // 并且beanName不以.ORIGINAL结尾,表示可能会为bean创建代理
   if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
      this.advisedBeans.put(cacheKey, Boolean.FALSE);
      return bean;
   }
 
   // Create proxy if we have advice.
    // 获取适用的advices
   Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
   if (specificInterceptors != DO_NOT_PROXY) {
      this.advisedBeans.put(cacheKey, Boolean.TRUE);
        // 能找到适用的advisor,则创建代理。
      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;
}
 
 
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
   List<Advisor> candidateAdvisors = findCandidateAdvisors();
    // 最终这里会返回BeanFactoryTransactionAttributeSourceAdvisor,切面逻辑是TransactionInterceptor
   List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
   extendAdvisors(eligibleAdvisors);
   if (!eligibleAdvisors.isEmpty()) {
      eligibleAdvisors = sortAdvisors(eligibleAdvisors);
   }
   return eligibleAdvisors;
}
 
 
// 从beanFactory中获取类型为Advisor.class的所有bean,并缓存在cachedAdvisorBeanNames中
public List<Advisor> findAdvisorBeans() {
   // Determine list of advisor bean names, if not cached already.
   String[] advisorNames = this.cachedAdvisorBeanNames;
   if (advisorNames == null) {
      // Do not initialize FactoryBeans here: We need to leave all regular beans
      // uninitialized to let the auto-proxy creator apply to them!
      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) {
      if (isEligibleBean(name)) {
         if (this.beanFactory.isCurrentlyInCreation(name)) {
            if (logger.isTraceEnabled()) {
               logger.trace("Skipping currently created advisor '" + name + "'");
            }
         }
         else {
            try {
               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;
}
 
 
protected List<Advisor> findAdvisorsThatCanApply(
      List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
 
   ProxyCreationContext.setCurrentProxiedBeanName(beanName);
   try {
      return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
   }
   finally {
      ProxyCreationContext.setCurrentProxiedBeanName(null);
   }
}
 
 
// Advisor,封装了切点和通知
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
   if (candidateAdvisors.isEmpty()) {
      return candidateAdvisors;
   }
   List<Advisor> eligibleAdvisors = new ArrayList<>();
   for (Advisor candidate : candidateAdvisors) {
        // IntroductionAdvisor主要是类级别的匹配
      if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
         eligibleAdvisors.add(candidate);
      }
   }
   boolean hasIntroductions = !eligibleAdvisors.isEmpty();
   for (Advisor candidate : candidateAdvisors) {
        // IntroductionAdvisor类型的上面已经处理过,这里跳过
      if (candidate instanceof IntroductionAdvisor) {
         // already processed
         continue;
      }
        // 其他类型的advisor
      if (canApply(candidate, clazz, hasIntroductions)) {
         eligibleAdvisors.add(candidate);
      }
   }
   return eligibleAdvisors;
}
 
 
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
    // 如果是IntroductionAdvisor类型,根据类过滤器来判断是否匹配
   if (advisor instanceof IntroductionAdvisor) {
      return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
   }
    // BeanFactoryTransactionAttributeSourceAdvisor属于PointcutAdvisor
   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");
    // TransactionAttributeSourcePointcut中的ClassFilter是TrueClassFilter,所有的类都匹配
   if (!pc.getClassFilter().matches(targetClass)) {
      return false;
   }
     
    // 如果methodMatcher是TrueMethodMatcher,所有方法都匹配
   MethodMatcher methodMatcher = pc.getMethodMatcher();
   if (methodMatcher == MethodMatcher.TRUE) {
      // No need to iterate the methods if we're matching any method anyway...
      return true;
   }
 
   IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
   if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
      introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
   }
 
    // 如果targetClass是代理类,则获取实际的Class
   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) :
                // 调用TransactionAttributeSourcePointcut的matches方法。最终利用SpringTransactionAnnotationParser来解析方法上的@Transactionl注解
               methodMatcher.matches(method, targetClass)) {
            return true;
         }
      }
   }
 
   return false;
}

相关文章

网友评论

      本文标题:5、Spring事务 生成代理

      本文链接:https://www.haomeiwen.com/subject/fvgkvctx.html