AOP五種增強執行時機及@around增強注意事情

AOP的執行時機,一共有五個。分別爲前置增強befor,後置增強after,返回後增強afterRunturning,異常後增強afterThorwing,環繞增強around

 

正如他們的名字一樣,前置增強是在目標方法執行之前執行,後置增強在目標方法執行之後執行,返回後增強在目標方法執行return之後執行,異常增強則是在目標方法拋出異常後執行,而環繞增強在它修飾的方法中可以同時實現以上所有增強。

前4個增強大致區別也就@後面跟哪個單詞的事情。具體體驗方法可以參考之前的那篇博客。我們重點看一下Around增強


	@Around(value = "execution(public int com.jd.CalculatorService.*(..))")
	public Object around (ProceedingJoinPoint joinPoint) {
		Object result = null;
		Object target = joinPoint.getTarget();
		String methodName = joinPoint.getSignature().getName();
		
		try {
			try {//前置增強
				System.out.println(target.getClass().getName()+": The"+methodName+"method begins");
	
				result = joinPoint.proceed();
			} finally {//後置增強
				System.out.println(target.getClass().getName()+":The "+methodName+" method ends.");
			}
                //返回增強
                System.out.println(target.getClass().getName()+":Result of the "+methodName+" method:"+result);
		} catch (Throwable e) {//異常增強
			System.out.println(target.getClass().getName()+":Exception of the method "+methodName+": "+e);
		}		
		return result;
	}

around包含的4個增強已經在上面標註了出來。

需要注意的是@Before、@After、@AfterRunning和@AfterThrowing修飾的方法可以通過聲明JoinPoint 類型參數變量獲取目標方法的信息(方法名、參數列表等信息);@Around修飾的方法必須聲明ProceedingJoinPoint類型的參數,該變量可以決定是否執行目標方法。

而中間的result = joinPoint.proceed();這一句是執行目標方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章