溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

spring中aop如何實現

發布時間:2021-09-28 13:40:18 來源:億速云 閱讀:160 作者:小新 欄目:開發技術

這篇文章主要介紹了spring中aop如何實現,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

aop實現原理簡介

首先我們都知道aop的基本原理就是動態代理思想,在設計模式之代理模式中有介紹過這兩種動態代理的使用與基本原理,再次不再敘述。

這里分析的是,在spring中是如何基于動態代理的思想實現aop的。為了方便了解接下來的源碼分析,這里簡單化了一個流程圖分析aop的基本實現思想。

spring中aop如何實現

so,基于上面的流程,一步步分析spring源碼中的aop實現方式。

采用一個簡單的aop例子,利用基于注解配置方式的切面配置,分析一個簡單的Before AOP例子。在spring boot下運行以下簡單例子。

AOP的advisor和advice配置。

@Component
@Aspect
public class AopConfig {
    @Pointcut("execution(* com.garine.debug.testcase.model.AopObject..*(..))")
    public void mypoint(){
        //切面定義
    }
    @Before("mypoint()")
    public void doAround() throws Throwable {
        System.out.println("before logic");
    }
}

AopObject,被代理攔截對象。

@Component
public class AopObject {
    public void aoped(){
        System.out.println("logic");
    }
}

代理實現的處理器(BeanPostProcessor)

首先是第一步內容,對我們在AopConfig中的AOP配置內容進行解析并且保存到BeanFactory中,這個過程就是解析保存切面信息。

代理實現的源頭–AnnotationAwareAspectJAutoProxyCreator

經過一遍的代碼跟蹤,我了解到注解方式的AOP配置,都離不開一個類–AnnotationAwareAspectJAutoProxyCreator,這個類繼承了BeanPostProcessor接口,我們都知道BeanPostProcessor的實現類有多個執行處理節點,其中一個執行節點就是在Bean實例化之后。也就是在這個時機AnnotationAwareAspectJAutoProxyCreator攔截bean的初始化過程,根據提前解析得到的切面信息,對bean的方法進行嘗試適配,如果有匹配則需要進行代理創建。

這里先分析的就是AnnotationAwareAspectJAutoProxyCreator,在bean實例化第一次查詢所有切面信息時,就會解析保存Aop的信息到實例中,跟蹤以下代碼。

AbstractApplicationContext#refresh (上下文初始化主干方法)

AbstractApplicationContext#registerBeanPostProcessors (執行實例化并保存所有實現BeanPostProcessor接口的類)

按照上面的邏輯,registerBeanPostProcessors 會比一般的bean實例化邏輯要早執行,因此我們接下來只需要分析AnnotationAwareAspectJAutoProxyCreator的初始化過程。

AnnotationAwareAspectJAutoProxyCreator的繼承結構

spring中aop如何實現

通過上圖可以知道,AnnotationAwareAspectJAutoProxyCreator是繼承了BeanfactoryAware接口,所以在實例化時,會執行setFactory方法。而所有切面信息解析的執行者BeanFactoryAspectJAdvisorsBuilderAdapter初始化的時機也是在setFactory方法。

跟蹤代碼如下。

AbstractAdvisorAutoProxyCreator#setBeanFactory

AnnotationAwareAspectJAutoProxyCreator#initBeanFactory

在這個方法里面會新建一個BeanFactoryAspectJAdvisorsBuilderAdapter,這個對象會根據Beanfactory內的aop配置信息,進行解析保存。但是需要注意,此時雖然新建了BeanFactoryAspectJAdvisorsBuilderAdapter對象.但是此時還不會馬上解析aop配置,需要在第一次個普通bean實例化時才執行解析aop配置。解析的方法就是

BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors,會在初次執行AnnotationAwareAspectJAutoProxyCreator調用postProcessBeforeInitialization時開始執行。

protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   super.initBeanFactory(beanFactory);
    //aspectJAdvisorsBuilder#buildAspectJAdvisors就是解析配置入口
   this.aspectJAdvisorsBuilder =
         new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
}

代理對象(Proxy)的創建

解析并緩存切面

上面提到繼承結構圖中,AnnotationAwareAspectJAutoProxyCreator是實現了InstantiationAwareBeanPostProcessor接口的,InstantiationAwareBeanPostProcessor接口定義的postProcessBeforeInitialization方法是一個可以對已經注入依賴屬性的bean對象實例進行編輯操作的接口,會在

AbstractAutowireCapableBeanFactory#doCreateBean

AbstractAutowireCapableBeanFactory#initializeBean(String, Object, RootBeanDefinition)

AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInstantiation

方法中執行InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation,初次初始化緩存切面信息的話就是在這個方法里面。。

具體的調用鏈如上所示。這里的postProcessBeforeInstantiation方法實際上是AnnotationAwareAspectJAutoProxyCreator的實例進行調用,AnnotationAwareAspectJAutoProxyCreator實現InstantiationAwareBeanPostProcessor接口。

下面進入InstantiationAwareBeanPostProcessor#postProcessBeforeInitialization方法分析代碼。

AbstractAutoProxyCreator#postProcessBeforeInstantiation

AspectJAwareAdvisorAutoProxyCreator#shouldSkip (關鍵代碼)

進入如下代碼AbstractAutoProxyCreator,這個實例也就是之前一開始初始化的AnnotationAwareAspectJAutoProxyCreator實例,進入實例的shouldSkip 方法

	@Override
	protected boolean shouldSkip(Class<?> beanClass, String beanName) {
		// TODO: Consider optimization by caching the list of the aspect names
        //預先解析緩存切面信息
		List<Advisor> candidateAdvisors = findCandidateAdvisors();
		for (Advisor advisor : candidateAdvisors) {
			if (advisor instanceof AspectJPointcutAdvisor) {
				if (((AbstractAspectJAdvice) advisor.getAdvice()).getAspectName().equals(beanName)) {
					return true;
				}
			}
		}
		return super.shouldSkip(beanClass, beanName);
	}

AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors

方法findCandidateAdvisors代碼如下,這里是預先解析緩存所有切面advisor信息,注意這一步操作是在AbstractAutoProxyCreator#postProcessBeforeInitialization處理,也就是開頭提到的切面解析操作,解析完成就進行緩存。

@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.
    //這里就是前面提到的BeanFactoryAspectJAdvisorsBuilder解析所有切面信息的調用點
   advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
   return advisors;
}

然后繼續在這里先提前看一下是如何解析aop配置的。跟蹤BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors

public List<Advisor> buildAspectJAdvisors() {
   List<String> aspectNames = null;
   synchronized (this) {
      aspectNames = this.aspectBeanNames;
      if (aspectNames == null) {
         List<Advisor> advisors = new LinkedList<Advisor>();
         aspectNames = new LinkedList<String>();
          //查詢出Beanfactory中所有已經注冊的BeanName
         String[] beanNames =
               BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Object.class, true, false);
         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);
            if (beanType == null) {
               continue;
            }
             //判斷Bean是否是切面Bean,isAspect方法判斷[標注1]
            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);
                   //解析aop class的配置,包返回Advisor對象[標注2]
                  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 {
                  // Per target or per this.
                  if (this.beanFactory.isSingleton(beanName)) {
                     throw new IllegalArgumentException("Bean with name '" + beanName +
                           "' is a singleton, but aspect instantiation model is not singleton");
                  }
                  MetadataAwareAspectInstanceFactory factory =
                        new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
                  this.aspectFactoryCache.put(beanName, factory);
                  advisors.addAll(this.advisorFactory.getAdvisors(factory));
               }
            }
         }
         this.aspectBeanNames = aspectNames;
         return advisors;
      }
   }
   if (aspectNames.isEmpty()) {
      return Collections.emptyList();
   }
   List<Advisor> advisors = new LinkedList<Advisor>();
   for (String aspectName : aspectNames) {
      List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
      if (cachedAdvisors != null) {
         advisors.addAll(cachedAdvisors);
      }
      else {
         MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
         advisors.addAll(this.advisorFactory.getAdvisors(factory));
      }
   }
   return advisors;
}

**[標注1]如何判斷類是否是aop切面配置類? **

通過以下代碼。

@Override
public boolean isAspect(Class<?> clazz) {
   return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));
}
private boolean hasAspectAnnotation(Class<?> clazz) {
    //包含@Aspect注解
   return (AnnotationUtils.findAnnotation(clazz, Aspect.class) != null);
}

[標注2]如何解析為Advisor對象?

ReflectiveAspectJAdvisorFactory#getAdvisors 遍歷所有沒被@PointCut注解標注的方法,也就是遍歷切面內容方法

ReflectiveAspectJAdvisorFactory#getAdvisor 處理所有沒被@PointCut注解標注的方法,候選切面內容方法

代碼如下。

@Override
public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,
      int declarationOrderInAspect, String aspectName) {
   validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());
   //解析判斷候選方法是否有@Before,@After,@Around等注解,如果有,就繼續執行新建Advisor對象。
   AspectJExpressionPointcut expressionPointcut = getPointcut(
         candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
   if (expressionPointcut == null) {
      return null;
   }
//創建advisor
   return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
         this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
}

最終循環解析,@Before,@After,@Around等標注的方法都會新建一個Advisor對象。新建的Advisor對象都保存在BeanFactoryAspectJAdvisorsBuilder#advisorsCache中,當AnnotationAwareAspectJAutoProxyCreator攔截bean的創建過程時,從這里面適配是否有切面可用。

這里解析得到的Advisor,大概有以下信息。下面的信息中,并沒有對@PointCut注解做處理,pointCut屬性只得出一個"mypoint()",此時還不知道Advisor實際對應的攔截表達式。

spring中aop如何實現

攔截表達式還是空的,會在AnnotationAwareAspectJAutoProxyCreator#postProcessAfterInstantiation第一次執行時解析攔截表達式。

spring中aop如何實現

適配切面

在AbstractAutoProxyCreator#postProcessAfterInitialization執行時,找到上面AbstractAutoProxyCreator#postProcessBeforeInitialization緩存的所有的切面信息,之后是如何進行切面適配,從而決定是否需要進行代理對象的創建呢?

在調用AbstractAutoProxyCreator#postProcessAfterInitialization方法時,進行切面適配,并且會根據適配創建代理對象。根據以下調用鏈。

AbstractAutoProxyCreator#postProcessAfterInitialization

AbstractAutoProxyCreator#wrapIfNecessary

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
   if (beanName != null && 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;
}

AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean

AbstractAdvisorAutoProxyCreator#findEligibleAdvisors

protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
    //從緩存取出所有切面信息
   List<Advisor> candidateAdvisors = findCandidateAdvisors();
    //根據advisor信息中的表達式進行方法對class的匹配
   List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
   extendAdvisors(eligibleAdvisors);
   if (!eligibleAdvisors.isEmpty()) {
      eligibleAdvisors = sortAdvisors(eligibleAdvisors);
   }
   return eligibleAdvisors;
}

此時如果是第一次執行適配方法findAdvisorsThatCanApply的話,candidateAdvisors中的攔截表達式還是空的,需要進行表達式獲取,也就是@Pointcut的value。spring的操作的在第一次執行findAdvisorsThatCanApply時解析獲取攔截表達式的值,獲得攔截表達式值之后就跟當前class的方法進行匹配看是否需要進行代理。

繼續往下跟蹤代碼

AopUtils#canApply(org.springframework.aop.Advisor, java.lang.Class<?>, boolean)

AopUtils#canApply(org.springframework.aop.Pointcut, java.lang.Class<?>, boolean)

AspectJExpressionPointcut#getClassFilter

AspectJExpressionPointcut#checkReadyToMatch

private void checkReadyToMatch() {
   if (getExpression() == null) {
      throw new IllegalStateException("Must set property 'expression' before attempting to match");
   }
   if (this.pointcutExpression == null) {
      this.pointcutClassLoader = (this.beanFactory instanceof ConfigurableBeanFactory ?
            ((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader() :
            ClassUtils.getDefaultClassLoader());
       //解析得到攔截表達式,例如根據@Before的value來關聯查詢出對應的表達式
      this.pointcutExpression = buildPointcutExpression(this.pointcutClassLoader);
   }
}

最終解析完之后,advisor中的表達式信息結構如下圖。包含在pointcut屬性中,匹配時就根據pointcutExpression循環進行匹配class的方法。有興趣的可以繼續調試看看是如何實現匹配表達式的。

spring中aop如何實現

##  創建代理對象

如果在上面的匹配切面過程中,發現適配的切面,那就需要進行代理對象的創建了。

我們回到上面的AbstractAutoProxyCreator#wrapIfNecessary,主要看代碼如下。

  // 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;
   }

所以,繼續看

AbstractAutoProxyCreator#createProxy

的創建代理對象方法。設置ProxyFactory創建Proxy需要的一切信息。

protected Object createProxy(
      Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
   if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
      AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
   }
    //新建代理對象工廠
   ProxyFactory proxyFactory = new ProxyFactory();
   proxyFactory.copyFrom(this);
    //設置工廠代理類
   if (!proxyFactory.isProxyTargetClass()) {
      if (shouldProxyTargetClass(beanClass, beanName)) {
         proxyFactory.setProxyTargetClass(true);
      }
      else {
         evaluateProxyInterfaces(beanClass, proxyFactory);
      }
   }
    //設置攔截切面
   Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
   for (Advisor advisor : advisors) {
      proxyFactory.addAdvisor(advisor);
   }
    //設置被代理對象
   proxyFactory.setTargetSource(targetSource);
   customizeProxyFactory(proxyFactory);
   proxyFactory.setFrozen(this.freezeProxy);
   if (advisorsPreFiltered()) {
      proxyFactory.setPreFiltered(true);
   }
//創建代理對象
   return proxyFactory.getProxy(getProxyClassLoader());
}

下面看ProxyFactory是如何創建代理對象,繼續跟蹤proxyFactory.getProxy(getProxyClassLoader());

public Object getProxy(ClassLoader classLoader) {
   return createAopProxy().getProxy(classLoader);
}

createAopProxy()作用是根據class的種類判斷采用的代理方式,看如下實現

DefaultAopProxyFactory#createAopProxy

@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
	if (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)) {
            //采用jdk動態代理必須基于接口
			return new JdkDynamicAopProxy(config);
		}
        //基于cglib實現代理不需要接口
		return new ObjenesisCglibAopProxy(config);
	}
	else {
		return new JdkDynamicAopProxy(config);
	}
}

所以在當前調試的例子中,使用cglib代理。所以執行如下代理。

@Override
public Object getProxy(ClassLoader classLoader) {
     //。。。。。。
      // Configure CGLIB Enhancer...
      Enhancer enhancer = createEnhancer();
      if (classLoader != null) {
         enhancer.setClassLoader(classLoader);
         if (classLoader instanceof SmartClassLoader &&
               ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
            enhancer.setUseCache(false);
         }
      }
      enhancer.setSuperclass(proxySuperClass);
      enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
      enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
      enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
	//獲取攔截回調函數
      Callback[] callbacks = getCallbacks(rootClass);
      Class<?>[] types = new Class<?>[callbacks.length];
      for (int x = 0; x < types.length; x++) {
         types[x] = callbacks[x].getClass();
      }
      // fixedInterceptorMap only populated at this point, after getCallbacks call above
      enhancer.setCallbackFilter(new ProxyCallbackFilter(
            this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
      enhancer.setCallbackTypes(types);
      // Generate the proxy class and create a proxy instance.
    //返回一個cglib代理對象
      return createProxyClassAndInstance(enhancer, callbacks);
   }
   catch (CodeGenerationException ex) {
       //、、、、、、
   }
}

getCallbacks(rootClass);在這個獲取回調函數的方法中,普通的aop采用的回調函數是如下的方式。

// Choose an "aop" interceptor (used for AOP calls).
Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);

cglib 的aop回調函數如下。

public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
   Object oldProxy = null;
   boolean setProxyContext = false;
   Class<?> targetClass = null;
   Object target = null;
   try {
       //這里注入的advised就是之前創建的ProxyFactory對象
      if (this.advised.exposeProxy) {
         // Make invocation available if necessary.
         oldProxy = AopContext.setCurrentProxy(proxy);
         setProxyContext = true;
      }
      // May be null. Get as late as possible to minimize the time we
      // "own" the target, in case it comes from a pool...
      target = getTarget();
      if (target != null) {
         targetClass = target.getClass();
      }
       //根據切面信息創建切面內容調用鏈
      List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
      Object retVal;
      // Check whether we only have one InvokerInterceptor: that is,
      // no real advice, but just reflective invocation of the target.
      if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
         // We can skip creating a MethodInvocation: just invoke the target directly.
         // Note that the final invoker must be an InvokerInterceptor, so we know
         // it does nothing but a reflective operation on the target, and no hot
         // swapping or fancy proxying.
         Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
         retVal = methodProxy.invoke(target, argsToUse);
      }
      else {
         // We need to create a method invocation...
          //創建一個方法調用對象,具體調用實現沒分析,Before邏輯大概是先調用切面,在反射調用目標方法
         retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
      }
      retVal = processReturnType(proxy, target, method, retVal);
      return retVal;
   }
   finally {
      if (target != null) {
         releaseTarget(target);
      }
      if (setProxyContext) {
         // Restore old proxy.
         AopContext.setCurrentProxy(oldProxy);
      }
   }
}

感謝你能夠認真閱讀完這篇文章,希望小編分享的“spring中aop如何實現”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女