Spring學習筆記(二)–AOP

來源:互聯網
上載者:User

一.概論

從圖上可以看出,Spring AOP的所有概念基本分為三塊:

第一塊(左上方)為AOP配置,主要包含ProxyConfig,AdvisedSupport,這些配置包含AOP主要概念如target(目的對象),Advisors(切入點及其對應的增強)構成的處理鏈。

第二塊為(右上方)AOPProxyFactory這主要是沿用了spring的主要思想即構造主要都採用factoryBean封裝,可以產生不同的AopProxy,如Cglib2AopProxy,JdkDynamicProxy.

第三塊(下方)為代理邏輯,包含Spring的InvocationHandler實現JdkDynamicProxy(主要實現調用攔截增強過程),Proxy(可根據InvocationHandler,目標對象實現介面組建代理程式類$Proxy0,$Proxy0為產生的代理類。

 

二、JDKDynamicProxy組建代理程式類$Proxy0分析:

1. 類組成部分:

  • 建構函式$Proxy0(InvocationHandler h)。
  • 成員變數InvocationHandler h
  • static Method m1,m2,m3,…,mn等儲存所有target實現介面的Method類型的欄位。
  • 方法 所有target實現介面內聲明的方法。

 

2. 實現代理原理:

在static方法塊中會將所有的介面中的所有方法全部給得到,並儲存在m1,m2,m3,...,mn欄位中,並且會產生介面中所有的方法.方法的實現為調用其作為成員變數的InvocationHander的invoke(Object proxy,Method method,Object[]args)方法,將參數和方法欄位mn傳入,進行調用。而一般來說target目標對象會調用相應的method,在這個調用過程中就會使用Advisor的責任鏈來進行多餘特性的植入。

 

三、調用增強過程:

以JDKDynamicProxy為例:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable

 

1. 從advised中得到targetSource。

 

2. 從advised中得到所有的Chain

org.springframework.aop.framework.DefaultAdvisorChainFactory

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(

Advised config, Method method, Class targetClass)

hasIntroductions 沒有

逐一查看config中所有的Adivisors

如果Advisor是PointcutAdvisor

看這個Advisor是否滿足ClassFilter

將Advisor轉換成MethodInterceptor

是則匹配方法從Pointcut中取MethodMatcher,使用MethodMatcher來匹配方法

 

3. 如果chain是空的,retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);

// We need to create a method invocation...

invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);

// Proceed to the joinpoint through the interceptor chain.

retVal = invocation.proceed();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.