1、定義
2、before(前置通知)
after和after-return和前置通知差不多,就不做解釋了。
普通前置通知
<aop:before method="BeforeInsert" pointcut-ref="studentPointcut"/>
//通知方法
public void BeforeInsert(JoinPoint joinPoint){ System.out.println(joinPoint); System.out.println("BeforeInsert as LogImpl"); }
我們也可以在這里獲取連接點方法的參數值。
連接點
public int add(int num1,int num2){ return num1+num2; }
通知
public void beforeInsert(JoinPoint joinPoint,int n,int m){ System.out.println(n); System.out.println(m); System.out.println(joinPoint); System.out.println("BeforeInsert as LogImpl"); }
xml
<aop:config> <!--切點表達式中添加and 設置別名,可以設置和通知方法的參數名一樣的--> <aop:pointcut id="studentPointcut" expression="execution(* com.target.StudentDaoImpl.*(..)) and args(n,m)"/> <aop:aspect id="logAspect" ref="log"> <!--arg-names對應切點表達式的別名--> <aop:before method="beforeInsert" pointcut-ref="studentPointcut" arg-names="n,m"/> </aop:aspect> </aop:config>
切點表達式設置了args(n,m),那么其它通知也需要添加對應的方法參數和設置arg-names
<aop:after-throwing method="throwInsert" pointcut-ref="studentPointcut" throwing="ey"/>
throwing指定異常類型參數
public void throwInsert(RuntimeException ey) { System.out.println("throwException"); }
異常通知方法設置了異常參數,throwing需要設置跟異常參數,目標方法產生的異常是此通知異常類型或子類型時,該通知方法才會被使用。
<aop:around method="aroundInsert" pointcut-ref="studentPointcut"/>
通知方法:
public Object aroundInsert(ProceedingJoinPoint joinPoint){ //相當於before System.out.println("Before...."); //定義result保存調用方法結果 Object result = null; try { //調用方法 result = joinPoint.proceed(); //相當於after-return System.out.println("after-return...."); } catch (Throwable throwable) { throwable.printStackTrace(); //相當於throwing System.out.println("throwing...."); } //相當於after System.out.println("after...."); //返回結果 return result; }
around一般使用比較多,因為它包含了上面四種的功能。
ProceedingJoinPoint 一般作為環繞通知方法的參數,它實現了JoinPoint接口,增強版。可以控制目標方法的執行
以及查看目標方法的參數等等。
JoinPoint作為上面四種通知的參數。它包含了一系列的目標方法的信息。