美文网首页JAVA基础springboot
《Spring(5.x)注解驱动开发》aop(三)

《Spring(5.x)注解驱动开发》aop(三)

作者: 曦夫 | 来源:发表于2019-01-18 17:16 被阅读21次

20.AOP原理总结

  1. 利用@EnableAspectJAutoProxy开启AOP功能。
  2. @EnableAspectJAutoProxy注解给容器注册一个组件AnnotationAwareAspectJAutoProxyCreator
  3. AnnotationAwareAspectJAutoProxyCreator是一个后置处理器。
  4. 容器的创建流程:
    1. 在 registerBeanPostProcessors(beanFactory)步骤中注册后置处理器;创建AnnotationAwareAspectJAutoProxyCreator对象。
    2. 在finishBeanFactoryInitialization(beanFactory);步骤中初始化剩下的单实例bean,
      ①.创建业务逻辑组件和切面组件
      ②.AnnotationAwareAspectJAutoProxyCreator拦截组件的创建过程
      ③.组件创建完成后,判断组件是否需要增强
      ⅰ. 若需要增强,切面的通知方法,会包装成增强器(Advisor),给业务逻辑组件创建一个代理对象(cglib)
  5. 执行目标方法
    1. 代理对象执行目标方法

    2. CglibAopProxy.intercept():
      ①.得到目标方法的拦截器链(增强器包装成拦截器MethodInterceptor)
      ②.利用拦截器的链式机制,依次进入每一个拦截器执行,先执行
      正常执行:前置通知 -> 目标方法 -> 后置通知 -> 返回通知
      异常执行:前置通知 -> 目标方法 -> 后置通知 -> 异常通知

21.AOP原理问题详解

  1. BeanPostProcessor:后置处理器
    1.1 BeanPostProcessor作用:
      我们需要在Spring容器完成Bean的实例化、配置和其他的初始化前后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProcessor接口的实现,然后注册到容器中。
    1.2. BeanPostProcessor结构图

    BeanPostProcessor结构图
    1.3. BeanPostProcessor与InstantiationAwareBeanPostProcessor
    1. BeanPostProcessor接口有两个方法
      postProcessBeforeInitialization:初始化bean之前调用
      postProcessAfterInitialization:初始化bean之后调用
    2. InstantiationAwareBeanPostProcessor接口
      postProcessBeforeInstantiation:实例化bean之前调用
      postProcessAfterInstantiation:实例化bean之后调用
    3. 区别
      ①.BeanPostProcessor作用于bean生命周期的初始化前后,即对bean属性赋值
      ②.InstantiationAwareBeanPostProcessor作用于bean实例化前后,即创建bean对象
    4. 联系
      InstantiationAwareBeanPostProcessor接口继承BeanPostProcessor接口,是其子接口,且InstantiationAwareBeanPostProcessor拥有父接口功能。
  2. AnnotationAwareAspectJAutoProxyCreator后置处理器
    2.1. AnnotationAwareAspectJAutoProxyCreator后置处理器作用
      在使用@EnableAspectJAutoProxy注解开启Aop后被注入到容器中的后置处理器。它实现了InstantiationAwareBeanPostProcessor接口,所以在Bean的实例化前后起作用。

    2.2. AnnotationAwareAspectJAutoProxyCreator继承树


    AnnotationAwareAspectJAutoProxyCreator继承树
  3. Aware接口
    3.1. Aware接口的作用
      1. Aware接口是自我感知的意思,即任何实现Aware接口的bean都可以得到该bean自身的属性.
      2. Spring中提供了很多XxxAware接口,由于这些接口中有且只有一个setXxx()的方法,来给是实现该接口的类的Xxx设置属性值。例如BeanFactoryAware接口。任何实现了该接口的bean都可以获取BeanFactory来实现w往bean中注入BeanFactory.
      3. 各种XxxAware接口的实际价值,是在我们需要用到spring内部定义的一些Bean来获取一些资源的时候,帮我们将这些bean注入进来。 但这也增加了bean与spring框架的耦合。
    3.2. Aware接口子接口继承图

    Aware接口子接口继承图

相关文章

网友评论

    本文标题:《Spring(5.x)注解驱动开发》aop(三)

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