找回密码
 立即注册
首页 业界区 安全 Spring IOC 源码学习 事务增强相关的对象创建 ...

Spring IOC 源码学习 事务增强相关的对象创建

辈霖利 昨天 04:35
事务增强相关的对象创建

internalAutoProxyCreator 对象

首先是 internalAutoProxyCreator 它是负责创建AOP对象 它本身是BPP, 它会在 registerBeanPostProcessors(beanFactory); 过程中被实例化
org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, org.springframework.context.support.AbstractApplicationContext)
  1.         /**
  2.          *  in short:
  3.          *  1. 拿到所有实现 BeanPostProcessor 的 bean, 然后进行分类存起来
  4.          *  这有一点, Spring 对 BeanDefinition 分成三种角色:
  5.          *          1. 用户定义的 Bean (ROLE_APPLICATION)
  6.          *      2. 较复杂的 (ROLE_SUPPORT) 较复杂的? 通常是一个外部配置
  7.          *      3. Spring 内置的(ROLE_INFRASTRUCTURE)
  8.          *  2. 如果实现了 BeanPostProcessor 则会实例化这个bean, 但注意这里只是注册,并不会调用BeanPostProcessor的相关方法
  9.          *
  10.          *  另外 BeanPostProcessor 粗粒度太大, Spring 还细分一些子接口:
  11.          *  - SmartInstantiationAwareBeanPostProcessor 它提供了更高级的Bean实例化控制方法。主要作用在于允许对Bean的实例化过程进行更精细的控制和定制。
  12.          *  - MergedBeanDefinitionPostProcessor 在合并Bean定义(MergedBeanDefinition)之后但在实例化Bean之前,允许对合并后的Bean定义进行修改、调整或附加元数据。
  13.          *  - DestructionAwareBeanPostProcessor 它允许在Bean被销毁之前(例如,容器关闭或特定作用域的Bean销毁)执行一些操作。
  14.          */
  15.         public static void registerBeanPostProcessors(
  16.                         ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
  17.                 // WARNING: Although it may appear that the body of this method can be easily
  18.                 // refactored to avoid the use of multiple loops and multiple lists, the use
  19.                 // of multiple lists and multiple passes over the names of processors is
  20.                 // intentional. We must ensure that we honor the contracts for PriorityOrdered
  21.                 // and Ordered processors. Specifically, we must NOT cause processors to be
  22.                 // instantiated (via getBean() invocations) or registered in the ApplicationContext
  23.                 // in the wrong order.
  24.                 //
  25.                 // Before submitting a pull request (PR) to change this method, please review the
  26.                 // list of all declined PRs involving changes to PostProcessorRegistrationDelegate
  27.                 // to ensure that your proposal does not result in a breaking change:
  28.                 // https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
  29.                 /**
  30.                  * 拿到所有实现 BeanPostProcessor 的 bean名称
  31.                  */
  32.                 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
  33.                 // Register BeanPostProcessorChecker that logs an info message when
  34.                 // a bean is created during BeanPostProcessor instantiation, i.e. when
  35.                 // a bean is not eligible for getting processed by all BeanPostProcessors.
  36.                 /**
  37.                  * 计算 BeanPostProcessor(BPP) 的总数.
  38.                  * +1 是什么操作? 原因是: 下一行,又加了一个 BeanPostProcessorChecker
  39.                  */
  40.                 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
  41.                 // BeanPostProcessorChecker 这个BeanPostProcessor, 没啥实际作用, 就是记录了一些日志;
  42.                 beanFactory.addBeanPostProcessor(
  43.                                 new BeanPostProcessorChecker(beanFactory, postProcessorNames, beanProcessorTargetCount));
  44.                 // Separate between BeanPostProcessors that implement PriorityOrdered,
  45.                 // Ordered, and the rest.
  46.                 /**
  47.                  * 对 BeanPostProcessor 进行分类存起来,  再调用, 每个集合分别是
  48.                  * 1. priorityOrderedPostProcessors //有实现(PriorityOrdered)排序接口的
  49.                  * 2. internalPostProcessors //Spring内部的bean, 见: Spring将bean分为三种角色
  50.                  * 3. orderedPostProcessorNames //实现 Ordered 接口
  51.                  * 4. nonOrderedPostProcessorNames //没有指定顺序, 无序的
  52.                  */
  53.                 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  54.                 List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
  55.                 List<String> orderedPostProcessorNames = new ArrayList<>();
  56.                 List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  57.                 for (String ppName : postProcessorNames) {
  58.                         if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  59.                                 /**
  60.                                  * 注意, 若 bean 实现了 PriorityOrdered 接口, 则会优先实例化它;
  61.                                  */
  62.                                 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  63.                                 priorityOrderedPostProcessors.add(pp);
  64.                                 if (pp instanceof MergedBeanDefinitionPostProcessor) {
  65.                                         internalPostProcessors.add(pp);
  66.                                 }
  67.                         }
  68.                         else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  69.                                 orderedPostProcessorNames.add(ppName);
  70.                         }
  71.                         else {
  72.                                 nonOrderedPostProcessorNames.add(ppName);
  73.                         }
  74.                 }
  75.                 // First, register the BeanPostProcessors that implement PriorityOrdered.
  76.                 sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  77.                 registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
  78.                 // Next, register the BeanPostProcessors that implement Ordered.
  79.                 List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
  80.                 for (String ppName : orderedPostProcessorNames) {
  81.                         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  82.                         orderedPostProcessors.add(pp);
  83.                         if (pp instanceof MergedBeanDefinitionPostProcessor) {
  84.                                 internalPostProcessors.add(pp);
  85.                         }
  86.                 }
  87.                 sortPostProcessors(orderedPostProcessors, beanFactory);
  88.                 registerBeanPostProcessors(beanFactory, orderedPostProcessors);
  89.                 /**
  90.                  * 注册所有常规BeanPostProcessors
  91.                  * 这里 getBean 实例化bean !;
  92.                  */
  93.                 // Now, register all regular(常规) BeanPostProcessors.
  94.                 List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
  95.                 for (String ppName : nonOrderedPostProcessorNames) {
  96.                         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  97.                         nonOrderedPostProcessors.add(pp);
  98.                         if (pp instanceof MergedBeanDefinitionPostProcessor) {
  99.                                 internalPostProcessors.add(pp);
  100.                         }
  101.                 }
  102.                 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
  103.                 /**
  104.                  * 最后, 注册所有 内置 BeanPostProcessor
  105.                  */
  106.                 // Finally, re-register all internal BeanPostProcessors.
  107.                 sortPostProcessors(internalPostProcessors, beanFactory);
  108.                 registerBeanPostProcessors(beanFactory, internalPostProcessors);
  109.                 //最后再放一个 ApplicationListenerDetector 让它在最后 (不是重点, 见名应该是事件相关的)
  110.                 // Re-register post-processor for detecting inner beans as ApplicationListeners,
  111.                 // moving it to the end of the processor chain (for picking up proxies etc).
  112.                 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
  113.         }
复制代码
DefaultBeanFactoryPointcutAdvisor 和 AspectJExpressionPointcut 对象

internalAutoProxyCreator 会在 postProcessBeforeInstantiation 回调中的org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#shouldSkip判断时实例化所有的 Advisor
在实例化 Advisor 填充属性时也会把 AspectJExpressionPointcut 也实例化
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation
  1. @Override
  2.         public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
  3.                 /**
  4.                  * 常规情况下:  这里只是检查下缓存和标记缓存
  5.                  * 对于真正的AOP代理创建见:
  6.                  * {@link AbstractAutoProxyCreator#postProcessAfterInitialization(java.lang.Object, java.lang.String)}
  7.                  */
  8.                 Object cacheKey = getCacheKey(beanClass, beanName);
  9.                 if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
  10.                         /**
  11.                          *
  12.                          *  不管需不需要, 只要处理过了就缓存
  13.                          *         advisedBeans 这个变量, 缓存所有处理过的 bean名称;
  14.                          *         value 为 boolean值, 如果为false 则不处理
  15.                          */
  16.                         if (this.advisedBeans.containsKey(cacheKey)) {
  17.                                 return null;
  18.                         }
  19.                         /**
  20.                          * isInfrastructureClass 是否是基础功能类,即 AOP相关的几个类:
  21.                          * Advice.class Pointcut.class Advisor.class AopInfrastructureBean.class 都为true
  22.                          *
  23.                          * shouldSkip 判断时, 拿到容器的所有 Advisor, 并且实例化 `getBean()` 这个 Advisor
  24.                          */
  25.                         if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
  26.                                 this.advisedBeans.put(cacheKey, Boolean.FALSE);
  27.                                 return null;
  28.                         }
  29.                 }
  30.                 // Create proxy here if we have a custom TargetSource.
  31.                 // Suppresses unnecessary default instantiation of the target bean:
  32.                 // The TargetSource will handle target instances in a custom fashion.
  33.                 TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
  34.                 if (targetSource != null) {
  35.                         if (StringUtils.hasLength(beanName)) {
  36.                                 this.targetSourcedBeans.add(beanName);
  37.                         }
  38.                         Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
  39.                         Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
  40.                         this.proxyTypes.put(cacheKey, proxy.getClass());
  41.                         return proxy;
  42.                 }
  43.                 return null;
  44.         }
复制代码
TransactionInterceptort 对象

是在 internalAutoProxyCreator 遇到需要增强代理的对象时, 这里是 bookService  去 getAdvicesAndAdvisorsForBean 查找到其匹配 bookService 的 Advisor
这里若 Advisor 匹配, 会调用 getAdvice 获取其切面, 此时切面不存在则会实例化它
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
  1. protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
  2.                 if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
  3.                         return bean;
  4.                 }
  5.                 if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
  6.                         return bean;
  7.                 }
  8.                 if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
  9.                         this.advisedBeans.put(cacheKey, Boolean.FALSE);
  10.                         return bean;
  11.                 }
  12.                 /**
  13.                  * 拿到所有匹配织入当前bean的 所有通知器(Advisor)
  14.                  * 做了三件事, 见: {@link org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean(java.lang.Class, java.lang.String, org.springframework.aop.TargetSource)}
  15.                  * 1. 往返回 `AspectJXXXAdvice`列表数组`0`索引 插入一个{@link org.springframework.aop.interceptor.ExposeInvocationInterceptor} 实例
  16.                  * 方便传递参数用的
  17.                  *
  18.                  * 2. 怎么匹配(Advisor)?
  19.                  * Advisor中的 `AspectJExpressionPointcut` 是实现 {@link ClassFilter} 和 {@link org.springframework.aop.MethodMatcher} 接口
  20.                  * 一个进行类匹配, 一个进行方法匹配. Advisor 匹配会调用 getAdvice 获取其切面, 此时切面不存在则会实例化
  21.                  *
  22.                  * 3.  排序, 基于 `有向无环` 图进行排序; 可能匹配到多个切面(aspect)
  23.                  *
  24.                  */
  25.                 // Create proxy if we have advice.
  26.                 Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
  27.                 if (specificInterceptors != DO_NOT_PROXY) {
  28.                         /**
  29.                          *{@link org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#advisedBeans}
  30.                          * 这个变量缓存所有处理过的 bean名称, value 为 boolean值, 如果为false 则不处理
  31.                          */
  32.                         this.advisedBeans.put(cacheKey, Boolean.TRUE);//缓存, 表示已处理
  33.                         /**
  34.                          * 创建代理
  35.                          *
  36.                          */
  37.                         Object proxy = createProxy(
  38.                                         bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
  39.                         this.proxyTypes.put(cacheKey, proxy.getClass());
  40.                         return proxy;
  41.                 }
  42.                 this.advisedBeans.put(cacheKey, Boolean.FALSE);
  43.                 return bean;
  44.         }
复制代码
汇总图

1.jpg


来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册