今天在項目中成功實現了spring aop 。
@Before @After @AfterReturning @Around @AfterThrowing
這五個是實現spring aop常用的五個注解
相關的注解還有@Aspect @Component @PointCut
我在實踐中發現:
1.@Before @After @AfterReturning @Around 這四個通知只有用一種,如果使用兩種及以上會發生一些問題。
2.@@PointCut 注解的方法不會被執行,只起到了一個把切面表達式抽象出來的作用。
3.@AfterReturning是最常用的:
使用 JointPoint.getArgs()可以獲取執行目標方法時傳入的參數。(同@Before @After @Around @AfterThrowing)
@AfterReturning注解中的returning = "object"應該和形參的object名字一致 ,用來接收目標方法的返回值。
@AfterReturning(pointcut="execution(...) " returning="object") public void afterReturning(JointPoint jp,Object object){
//注意這里的object 應該和returning="object"保持一致 System.out.println(object); //object是目標方法返回的參數 System.out.println(jp.getArgs() ); //通過這種方法可以獲取目標方法的傳入參數 }
下面是更具體的內容:
@Aspect @Componet public class myPointCut{ @Before("execution(...) ") public void before(){ System.out.println("前置通知:在目標方法執行前執行" ); } @After("execution(...) ") public void after(){ System.out.println("后置通知:在目標方法執行后執行" ); } @Around("execution(...) ") public void around(){ System.out.println("環繞通知:在目標方法執行前后都執行" ); } @AfterReturning(pointcut="execution(...) " returning="object") public void afterReturning(JointPoint jp,Object object){
//注意這里的object 應該和returning="object"保持一致 System.out.println(object); //object是目標方法返回的參數 System.out.println(jp.getArgs() ); //通過這種方法可以獲取目標方法的傳入參數 } @AfterThrowing("execution(...) ") public void afterThrowing(){ System.out.println("異常通知:在目標方法發生異常時執行" ); } }