环绕通知
環(huán)繞通知
環(huán)繞通知是所有通知類型中功能最為強(qiáng)大的, 能夠全面地控制連接點(diǎn). 甚至可以控制是否執(zhí)行連接點(diǎn).
對于環(huán)繞通知來說, 連接點(diǎn)的參數(shù)類型必須是 ProceedingJoinPoint . 它是 JoinPoint 的子接口, 允許控制何時(shí)執(zhí)行, 是否執(zhí)行連接點(diǎn).
在環(huán)繞通知中需要明確調(diào)用 ProceedingJoinPoint 的 proceed() 方法來執(zhí)行被代理的方法. 如果忘記這樣做就會導(dǎo)致通知被執(zhí)行了, 但目標(biāo)方法沒有被執(zhí)行.
注意: 環(huán)繞通知的方法需要返回目標(biāo)方法執(zhí)行之后的結(jié)果, 即調(diào)用 joinPoint.proceed(); 的返回值, 否則會出現(xiàn)空指針異常
package com.learn.spring.aspectJ;import java.util.Arrays;import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;/*** 日志切面*/ @Component //標(biāo)識為組件 @Aspect //標(biāo)識為切面 @Order(3) //指定切面的優(yōu)先級. 值越小,優(yōu)先級越高. 標(biāo)注@Order的切面比不標(biāo)注@Order切面的優(yōu)先級高 public class LoggingAspect {/*** 環(huán)繞通知:類似于動態(tài)代理的整個(gè)過程.*///@Around("execution(* com.learn.spring.aspectJ.*.*(..))")public Object aroundMethod(ProceedingJoinPoint pjp){String methodName = pjp.getSignature().getName();Object [] args = pjp.getArgs();try {System.out.println("The method "+methodName+" begins with " +Arrays.asList(args));//執(zhí)行目標(biāo)方法Object result = pjp.proceed();System.out.println("The method "+methodName+" ends with " +result );return result ;} catch (Throwable e) {e.printStackTrace();System.out.println("The method "+methodName+"occurs exception :" + e );}finally{System.out.println("The method " + methodName+"ends .");}return null ;}}?
超強(qiáng)干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)