自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

給冰冰看的SpringAOP面試題

開發(fā) 前端
Spring之前已經(jīng)跟學弟具體聊很詳細的IOC已經(jīng)循環(huán)依賴問題,接下來要接著為跟學妹們聊另外的一個模塊了,那就是AOP,這也是面試官比較喜歡問的一個模塊點。

[[422811]]

Spring之前已經(jīng)跟學弟具體聊很詳細的IOC已經(jīng)循環(huán)依賴問題,接下來要接著為跟學妹們聊另外的一個模塊了,那就是AOP,這也是面試官比較喜歡問的一個模塊點。

什么是AOP?

  • AOP通常叫面向切面編程(Aspect-oriented Programming,簡稱AOP),它是一種編程范式,通過預編譯的方式和運行期動態(tài)代理實現(xiàn)程序功能的統(tǒng)一維護的一種技術。
  • 通常用來對隔離不同業(yè)務邏輯,比如常見的事務管理、日志管理等。同時實現(xiàn)AOP的方式也有兩種:cglib 以及 jdk兩種方式來實現(xiàn)。

為什么要有AOP?

假設現(xiàn)在有幾個實現(xiàn)方法,需要做日志處理,正常來說我們只需要手動添加一下日志就可以了,我們都知道在真正的業(yè)務代碼中,代碼行數(shù),以及方法數(shù)那是一個天文數(shù)字,如果都要手動添加那工作量不現(xiàn)實。

本著作為程序員因該想著怎么合理的偷懶的習慣,所以應該想辦法提高效率。

AOP因此就產(chǎn)生了,說白了AOP就是通過某種匹配規(guī)則去匹配方法,然后再添加對應的日志處理。而AOP本身的實現(xiàn)方式就是通過ASM字節(jié)碼框架動態(tài)生成技術,在程序運行的時候,根據(jù)需求(添加文件)動態(tài)創(chuàng)建字節(jié)碼文件,之前講的設計模式中動態(tài)代理模式中也有講到,大家可以再去復習一下。

AOP的核心概念

切面(Aspect):似于 Java 中的類聲明,常用于應用中配置事務或者日志管理。一般使用 @Aspect 注解或者 來定義一個切面。

連接點(Join Point):程序執(zhí)行中的特定點,比如方法執(zhí)行、處理一個異常等

切點(Pointcut):通過一種規(guī)則匹配的正則表達式,當有連接點可以匹配到切點時,就會觸發(fā)改切點相關聯(lián)的指定通知。

通知(Advice):在切面中某個連接點采取的動作,通知方式也有5種

  • around(環(huán)繞通知):前后都加
  • before(前置通知)
  • after(后置通知)
  • exception(異常通知)
  • return(返回通知)

織入(Weaving):鏈接切面和目標對象創(chuàng)建一個通知對象的過程。

AOP其實就是一種編程思想,而這上面的這個點就是編程的具體實現(xiàn)規(guī)范。

一個應用中可以有多種通知方式所以在AOP中引入一種設計模式責任鏈模式通過這這種模式來順序執(zhí)行每一個通知當然也可以使用@Order注解,配置數(shù)字越小,越先執(zhí)行。關于責任鏈模式的大家也可以去看看我之前寫的設計模式復習一下。

AOP的執(zhí)行過程

之前跟大家聊IOC的時候跟大家聊過它的啟動過程,同樣的AOP也有指定的執(zhí)行流程,但是需要IOC作為基礎。

  • IOC容器啟動,用來存放對象
  • 進行對象的實例化和初始化操作,將生成的完成的對象存放到容器中(容器運行中的一些對象比如BeanFactoryProcesser、methodInterceptore等還有其他的很多對象)
  • 從創(chuàng)建好的容器中獲取需要對象
  • 調(diào)用具體的方法開始調(diào)用

說了這么多理論知識,要想知道里面的具體執(zhí)行流程,還是老樣子,一步一步debug進入源碼查看流程了

首先還是需要先準備配置一個切面

  1. @Aspect 
  2. @Component 
  3. public class LogUtil { 
  4.  
  5.     @Pointcut("execution(public * com.ao.bing.demo.spring.aop..*.*(..))"
  6.     public void pctMethod() { 
  7.     } 
  8.  
  9.     @Around(value = "pctMethod()"
  10.     public Object around(ProceedingJoinPoint pjp) throws Throwable { 
  11.         Object ret = pjp.proceed(); 
  12.         System.out.println("Around advice"); 
  13.         return ret; 
  14.     } 
  15.  
  16.     @Before("pctMethod()"
  17.     public void before() { 
  18.         System.out.println("Before advice"); 
  19.     } 
  20.  
  21.     @After(value = "pctMethod()"
  22.     public void after() { 
  23.         System.out.println("After advice"); 
  24.     } 
  25.  
  26.     @AfterReturning(value = "pctMethod()"
  27.     public void afterReturning() { 
  28.         System.out.println("AfterReturning advice"); 
  29.     } 
  30.  
  31.     @AfterThrowing(value = "pctMethod()"
  32.     public void afterThrowing() { 
  33.         System.out.println("AfterThrowing advice"); 
  34.     } 
  35.    
  36.    
  37.     // mian方法測試demo 
  38.       public static void main(String[] args) { 
  39.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); 
  40.         AopTestDemo aopTestDemo = applicationContext.getBean(AopTestDemo.class); 
  41.         aopTestDemo.method("測試AOP"); 
  42.  
  43.     } 

這里配置一個LogUtil的切面demo,五種通知都寫了一遍,同時也有一個main方法測試。準備工作做完了就正式開始debug代碼了

首先在aopTestDemo里面我們打上斷點,此時我們的過去的bean對象aopTestDemo已經(jīng)是通過動態(tài)代理生成的對象了,其中這里面有很多的CALLBACK方法屬性。那寫方法屬性是什么呢?

其實這里面就又跟Spring的攔截器有關,其實就是一種設計模式觀察者模式說白了就是對對象的一種行為的監(jiān)聽。通過回調(diào)機制來實現(xiàn)通知的功能。

那既然是回調(diào)方法,那就先進DynamicAdvisedInterceptor方法中

  1. private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable { 
  2.     private final AdvisedSupport advised; 
  3.  
  4.     public DynamicAdvisedInterceptor(AdvisedSupport advised) { 
  5.         this.advised = advised; 
  6.     } 
  7.  
  8.     @Nullable 
  9.     public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { 
  10.         Object oldProxy = null
  11.         boolean setProxyContext = false
  12.         Object target = null
  13.         TargetSource targetSource = this.advised.getTargetSource(); 
  14.  
  15.         Object var16; 
  16.         try { 
  17.             if (this.advised.exposeProxy) { 
  18.                 oldProxy = AopContext.setCurrentProxy(proxy); 
  19.                 setProxyContext = true
  20.             } 
  21.  
  22.             target = targetSource.getTarget(); 
  23.             Class<?> targetClass = target != null ? target.getClass() : null
  24.           // 從advised中 獲取配置好的AOP的通知方法 -重點 
  25.             List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); 
  26.             Object retVal; 
  27.           // 如果沒有配置通知方法,則直接調(diào)用target對象的調(diào)用方法 
  28.             if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) { 
  29.                 Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); 
  30.                 retVal = methodProxy.invoke(target, argsToUse); 
  31.             } else { 
  32.            // 通過CglibMethodInvocation來啟動advice通知 - 重點 
  33.                 retVal = (new CglibAopProxy.CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy)).proceed(); 
  34.             } 
  35.  
  36.             retVal = CglibAopProxy.processReturnType(proxy, target, method, retVal); 
  37.             var16 = retVal; 
  38.         } finally { 
  39.             if (target != null && !targetSource.isStatic()) { 
  40.                 targetSource.releaseTarget(target); 
  41.             } 
  42.  
  43.             if (setProxyContext) { 
  44.                 AopContext.setCurrentProxy(oldProxy); 
  45.             } 
  46.  
  47.         } 
  48.  
  49.         return var16; 
  50.     } 

在DynamicAdvisedInterceptor中有一個List chain這里獲取到我們配置的通知方法

從上面的截圖可以看到Spring先是把所有的通知獲取到,放在一個list集合對象中,因為此時list不為空所以就又會走到 通過CglibMethodInvocation來啟動advice通知這一步的流程中

  1. public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable { 
  2.  
  3.  protected final Object proxy; 
  4.  
  5.  @Nullable 
  6.  protected final Object target; 
  7.  
  8.  protected final Method method; 
  9.  
  10.  protected Object[] arguments = new Object[0]; 
  11.  
  12.  @Nullable 
  13.  private final Class<?> targetClass; 
  14.  
  15.  /** 
  16.   * Lazily initialized map of user-specific attributes for this invocation. 
  17.   */ 
  18.  @Nullable 
  19.  private Map<String, Object> userAttributes; 
  20.  
  21.  /** 
  22.   * List of MethodInterceptor and InterceptorAndDynamicMethodMatcher 
  23.   * that need dynamic checks. 
  24.   */ 
  25.  protected final List<?> interceptorsAndDynamicMethodMatchers; 
  26.  
  27.  /** 
  28.   * Index from 0 of the current interceptor we're invoking. 
  29.   * -1 until we invoke: then the current interceptor. 
  30.   */ 
  31.  private int currentInterceptorIndex = -1; 
  32.  
  33.  // 省略其他的方法 
  34.  
  35.  @Override 
  36.  @Nullable 
  37.  public Object proceed() throws Throwable { 
  38.   // We start with an index of -1 and increment early. 
  39.     // 從索引為-1的攔截器還是調(diào)用,并且按順序遞增,如果整個List chain中調(diào)用完畢,則開始調(diào)用target的函數(shù) 
  40.     // 具體的實現(xiàn)方式在AOPUtils.invokeJoinpointUsingRefection方法中,說白了就是通過反射實現(xiàn)目標方法 
  41.   if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { 
  42.    return invokeJoinpoint(); 
  43.   } 
  44.   // 獲取下一個需要執(zhí)行的攔截器,沿著定義好的interceptorOrInterceptionAdvice的鏈進行處理 
  45.   Object interceptorOrInterceptionAdvice = 
  46.     this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); 
  47.   if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) { 
  48.    // Evaluate dynamic method matcher here: static part will already have 
  49.    // been evaluated and found to match. 
  50.       // 對攔截器進行動態(tài)匹配,如果和定義的pointcut匹配 則就會執(zhí)行當前的這個advice 
  51.    InterceptorAndDynamicMethodMatcher dm = 
  52.      (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice; 
  53.    Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass()); 
  54.    if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) { 
  55.     return dm.interceptor.invoke(this); 
  56.    } 
  57.    else { 
  58.     // Dynamic matching failed. 
  59.     // Skip this interceptor and invoke the next in the chain. 
  60.     return proceed(); 
  61.    } 
  62.   } 
  63.   else { 
  64.    // It's an interceptor, so we just invoke it: The pointcut will have 
  65.    // been evaluated statically before this object was constructed. 
  66.       // 普通攔截器,直接調(diào)用攔截器,將當前的this(CglibMethodInvocation)作為參數(shù)保證當前實例中調(diào)用鏈的執(zhí)行 
  67.    return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); 
  68.   } 
  69.  } 
  70.  
  71.  // 省略其他的方法 

這里需要注意的一點 從上面的源碼中currentInterceptorIndex默認值定義為-1,相當于是作為判斷當前通知鏈式是執(zhí)行完成,執(zhí)行完那就是直接通過反射調(diào)用目標方法,否者向下接著執(zhí)行。

  • ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this)

interceptorOrInterceptionAdvice這個方法是關鍵點,即具體的調(diào)用攔截器去執(zhí)行具體的方法

  1. public final class ExposeInvocationInterceptor implements MethodInterceptor, PriorityOrdered, Serializable { 
  2.   
  3.  @Override 
  4.  public Object invoke(MethodInvocation mi) throws Throwable { 
  5.   MethodInvocation oldInvocation = invocation.get(); 
  6.   invocation.set(mi); 
  7.   try { 
  8.       // 具體執(zhí)行 
  9.    return mi.proceed(); 
  10.   } 
  11.   finally { 
  12.    invocation.set(oldInvocation); 
  13.   } 
  14.  } 

不知道大家發(fā)現(xiàn)了問題沒有,在剛上面截圖的時候List chain中有6個通知方法,而在配置的util中只配置了5個方法,第一個這就是ExposeInvocationInterceptor這個方法,那這個到底是啥呢?

  • 其實這里是Spring引入的又一個設計模式責任鏈設計模式引入這個設計模式原因就是在于,配置的通知方法這么多,那spring怎么知道去執(zhí)行那一個advice呢?所以通過ExposeInvocationInterceptor(暴露調(diào)用器的攔截器)作為第一個通知方法,來保證所以的通知方法按按這中連式方式執(zhí)行下去。

至此SpringAOP的通知連式結構調(diào)用流程就開始了,重復開始循環(huán)調(diào)用。一直到List chain整個鏈全部執(zhí)行完畢

當前這里面還有一些其他的邏輯需我就沒有具體細說了

比如整個鏈有沒有一種順序執(zhí)行?還是說根據(jù)代碼編寫的先后順序執(zhí)行?

  • org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator#sortAdvisors

在獲取到整個責任鏈之后會經(jīng)過一次排序執(zhí)行,這個排序默認是使用拓撲排序方法,大家可以具體的去看看sortAdvisors這個方法

然后在執(zhí)行每一種通知方法時,都會有對應的切面通知方法

  • org.springframework.aop.aspectj.AspectJAfterAdvice
  • org.springframework.aop.aspectj.AspectJAfterReturningAdvice
  • org.springframework.aop.aspectj.AspectJAfterThrowingAdvice
  • org.springframework.aop.aspectj.AspectJAroundAdvice
  • org.springframework.aop.aspectj.AspectJMethodBeforeAdvice

我們配置的五種通知對應著上面的五種處理邏輯

所以整個責任鏈來說通知調(diào)用鏈路可以理解為一張圖結構:

以上就是Spring通知整個執(zhí)行的過程,總結一下

  • Spring中的五種通知,首先是通過具Spring容器的啟動過程獲取到具體的通知,在調(diào)用對象時,通過動態(tài)代理ASM技術,把需要執(zhí)行的advice先全部放在一個chain對象的集合中,為了保證整個鏈的調(diào)用默認會先調(diào)用ExposeInvocationInterceptor去觸發(fā)整個鏈式執(zhí)行,在執(zhí)行完每一個advice時后都會再次回到super的proceed方法中,執(zhí)行下一個advice,在執(zhí)行不通的advice時后有對應的切面通知方法,當所有的advice執(zhí)行完畢再通過反射調(diào)用目標方法
  • 整個過程大家可以自己dubug試一下,也不是特別的麻煩!!!

AOP事務功能

AOP處理常見的配置切面處理日志等業(yè)務,還有大家也比較熟悉的那就是事務。

其實AOP的事務也是通過配置的advice的方式來執(zhí)行的

通知對advice的拆解來實現(xiàn)事務的功能。

  • 在看源碼的時候能給我們帶來很多的思考,對我們

在Spring中大家可以通過@Transactional注解來現(xiàn)實事務功能,看過源碼的同學肯定看過TransactionAspectSupport這個類

  1. public abstract class TransactionAspectSupport implements BeanFactoryAware, InitializingBean { 
  2.  // 省略其他代碼。。。。 
  3.  @Nullable 
  4.  protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass, 
  5.    final InvocationCallback invocation) throws Throwable { 
  6.  
  7.   // If the transaction attribute is null, the method is non-transactional. 
  8.   TransactionAttributeSource tas = getTransactionAttributeSource(); 
  9.   final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null); 
  10.   final PlatformTransactionManager tm = determineTransactionManager(txAttr); 
  11.   final String joinpointIdentification = methodIdentification(method, targetClass, txAttr); 
  12.  
  13.   if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) { 
  14.    // Standard transaction demarcation with getTransaction and commit/rollback calls. 
  15.    TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification); 
  16.    Object retVal = null
  17.    try { 
  18.     // This is an around advice: Invoke the next interceptor in the chain. 
  19.     // This will normally result in a target object being invoked. 
  20.     retVal = invocation.proceedWithInvocation(); 
  21.    } 
  22.    catch (Throwable ex) { 
  23.     // target invocation exception 
  24.         // 異?;貪L 重點 
  25.     completeTransactionAfterThrowing(txInfo, ex); 
  26.     throw ex; 
  27.    } 
  28.    finally { 
  29.     cleanupTransactionInfo(txInfo); 
  30.    }  
  31.       // 成功后提交 重點 
  32.    commitTransactionAfterReturning(txInfo); 
  33.    return retVal; 
  34.   } 
  35.   
  36.  // 省略其他的代碼。。。。 
  37.  

因此SpringAOP的聲明事務也是通過advice實現(xiàn)。

AOP的事務整體來說比較簡單,說白了就是通過advice的從新組合來完成事務功能,當然也是Spring的強大之處,擴展性是真的高。

總結

SpringAop就跟學妹們聊完了,需要理解的就是advice的通知整個流程,但是這個過程需要大家不斷的去看這個框架的源碼,看源碼的過程能給我們很多思考,怎么才能寫出高質量代碼?

為了加強理解,還是有兩個比較常見的面試題

advice的通知執(zhí)行流程?

  • 看完整個流程如果還是不理解我覺得可以自己debug走一遍加深自己的理解,文中我也做了總結。但是要自己真的理解才能不會被面試官問倒

AOP中的Transactional事務是怎么實現(xiàn)的?

  • 這個問題如果理解advice的調(diào)用流程那么也就能很簡單的回答了。

【編輯推薦】

 

責任編輯:姜華 來源: 三太子敖丙
相關推薦

2021-08-26 08:55:34

SpringIOC面試題

2021-08-10 08:45:27

SpringIOC面試題

2020-06-04 14:40:40

面試題Vue前端

2014-09-19 11:17:48

面試題

2023-11-13 07:37:36

JS面試題線程

2011-03-24 13:27:37

SQL

2020-11-16 07:22:32

騰訊多線程

2009-06-06 18:34:05

java面試題

2009-06-06 18:36:02

java面試題

2015-09-02 09:32:56

java線程面試

2014-07-15 11:10:01

面試題面試

2020-09-21 11:10:06

Docker運維面試

2010-11-26 10:53:29

戴爾

2017-09-13 07:15:10

Python讀寫文件函數(shù)

2018-09-11 14:20:06

數(shù)據(jù)庫Redis面試題

2025-02-26 07:58:41

2018-03-08 18:40:47

Java百度面試題

2023-07-14 08:12:21

計時器unsafecontext

2013-01-05 14:51:34

JavaScriptjQuery面試

2024-06-04 14:52:28

點贊
收藏

51CTO技術棧公眾號