异常通知
異常通知
只在連接點拋出異常時才執行異常通知
將 throwing 屬性添加到 @AfterThrowing 注解中, 也可以訪問連接點拋出的異常. Throwable 是所有錯誤和異常類的超類. 所以在異常通知方法可以捕獲到任何錯誤和異常.
如果只對某種特殊的異常類型感興趣, 可以將參數聲明為其他異常的參數類型. 然后通知就只在拋出這個類型及其子類的異常時才被執行.
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 //標識為組件 @Aspect //標識為切面 @Order(3) //指定切面的優先級. 值越小,優先級越高. 標注@Order的切面比不標注@Order切面的優先級高 public class LoggingAspect {/*** 異常通知:方法執行過程中拋出異常以后執行的.* * 可以指定拋出特定的異常再執行異常通知. 在形參的位置執行異常的類型即可.*///@AfterThrowing(value="execution(* com.learn.spring.aspectJ.*.*(..))",throwing="ex")public void afterThrowingMethod(JoinPoint joinPoint,ArithmeticException ex ){//獲取方法名:String methodName = joinPoint.getSignature().getName();System.out.println("The method "+methodName+" occurs exception:" + ex );}}?
總結