異常拋出通知使用@AfterThrowing
在切面類中配置:
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import java.math.BigInteger; @Aspect public class aspectj { // @Before(value = "execution(* com.AspecJ.xiaomaoDao.*(..))") // public void before(){ // System.out.println("我是前置通知!"); // } // @AfterReturning(value = "execution(* com.AspecJ.xiaomaoDao.delete())",returning = "element") // 使用returning來接受返回值 // public void After(Object element){ // System.out.println("我刪除了"+element); //打印輸出了返回值 // } // @Around(value="execution(* com.AspecJ.xiaomaoDao.update())") // public Object around(ProceedingJoinPoint joinPoint){ // Object obj=null; // System.out.println("環繞前"); // try { // obj=joinPoint.proceed(); // } catch (Throwable throwable) { // throwable.printStackTrace(); // } // System.out.println("環繞后"); // return obj; // } @AfterThrowing(value = "execution(* com.AspecJ.xiaomaoDao.find())",throwing = "throwinfo") public void throwafter(Throwable throwinfo){ System.out.println("發生了異常,異常信息如下:"); System.out.println(throwinfo.getMessage()); } }
目標類中的方法如下:
public class xiaomaoDao { public void save(){ System.out.println("save xiaomao!"); } public void find(){ System.out.println("find xiaomao!"); int i=1/0; } public String delete(){ System.out.println("delete xiaomao!"); return "xiaomao"; } public void update(){ System.out.println("update xiaomao!"); } }
執行后的結果如下:
delete xiaomao! find xiaomao! 發生了異常,異常信息如下: / by zero