springboot的aop

1、添加注解来支持spring aop

@EnableAspectJAutoProxy(proxyTargetClass = false)

2、在springboot里面, 自动支持aop,原因是spring.factories里面的

org.springframework.boot.autoconfigure.aop.AopAutoConfiguration

3、yml中添加配置支持aop(其实不添加配置也生效)

spring:
  aop:
    auto: true
    proxy-target-class: true

4、@EnableAspectJAutoProxy

->@Import(AspectJAutoProxyRegistrar.class)

可以看出@EnableAspectJAutoProxy引入了AspectJAutoProxyRegister.class对象 ,AspectJAutoProxyRegister给容器中注册一个AnnotationAwareAspectJAutoProxyCreator。AnnotationAwareAspectJAutoProxyCreator实现了InstantiationAwareBeanPostProcessor接口,所以每次创建bean实例前都会调用AnnotationAwareAspectJAutoProxyCreator类的postProcessBeforeInstantiation()方法。

参考博客:Spring源码阅读-AOP实现核心类AbstractAutoProxyCreator - 程小员的个人页面 - OSCHINA - 中文开源技术交流社区

 4.1、Advisor的获取:

首先获取spring bean中所有的Advisor

实现了Advisor接口(从spring容器中获取实现了Advisor接口的bean);

被@Aspect修饰的类转换成Advisor(遍历spring容器的所有bean,找出被@Aspect注解标记,并且有@PointCut注解的方法,生成切点AspectJExpressionPointcut)

public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,
      int declarationOrderInAspect, String aspectName) {

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

   AspectJExpressionPointcut expressionPointcut = getPointcut(
         candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
   if (expressionPointcut == null) {
      return null;
   }

   return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
         this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
}

 4.2、然后判断当前bean能否被增强   findAdvisorsThatCanApply -类+任一方法满足

4.3、通过ProxyFactory创建代理对象

4.4、生成org.springframework.aop.framework.JdkDynamicAopProxy(JDK动态代理)

当调用目标类的方法时,实际是执行的jdk动态代理的invoke方法,在里面遍历advisor,判断执行方法能否被切点切到(有没有被增强),获得MethodInterceptor的数组。

MethodBeforeAdvice -> MethodBeforeAdviceInterceptor(implements MethodInterceptor)

4.5、获取方法增强的责任链

5、设计模式

工厂模式

适配器模式

责任链模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值