Spring的注解的AOP的通知類型
- @Before:前置通知
- @AfterReturning:后置通知
- @Around:環繞通知
- @AfterThrowing:異常拋出通知
- @After:最終通知
- @Pointcut:切入點的注解
1 /** 2 * 切面類:注解的切面類 3 */ 4 @Aspect 5 public class MyAspectAnno { 6 //前置通知 7 @Before(value="execution(* com.itheima.spring.demo1.OrderDao.save(..) )") 8 public void before(){ 9 System.out.println("前置通知======"); 10 } 11 //后置通知 12 @AfterReturning(value="execution(* com.itheima.spring.demo1.OrderDao.delete(..))", returning="result") 13 public void afterReturning(Object result){ 14 System.out.println("后置通知====="+result); 15 } 16 @Around(value="execution(* com.itheima.spring.demo1.OrderDao.update(..))") 17 public Object around(ProceedingJoinPoint joinPoint) throws Throwable{ 18 System.out.println("環繞前增強====="); 19 Object obj = joinPoint.proceed(); 20 System.out.println("環繞后增強====="); 21 return obj; 22 } 23 //異常拋出通知 24 @AfterThrowing(value="execution(* com.itheima.spring.demo1.OrderDao.find(..))" , throwing="e") 25 public void find(Throwable e ){ 26 System.out.println("異常拋出通知======"+e.getMessage()); 27 } 28 //最終通知: 29 @After(value="execution(* com.itheima.spring.demo1.OrderDao.find(..))") 30 public void after( ){ 31 System.out.println("最終通知======"); 32 } 33 }
切入點的注解:
配置@Pointcut注解,使用類名.方法
/** * 切面類:注解的切面類 */ @Aspect public class MyAspectAnno { //切入點的注解 @Pointcut(value="execution(* com.itheima.spring.demo1.OrderDao.find(..))") private void pointcut1(){} @Pointcut(value="execution(* com.itheima.spring.demo1.OrderDao.save(..))") private void pointcut2(){} @Pointcut(value="execution(* com.itheima.spring.demo1.OrderDao.update(..))") private void pointcut3(){} @Pointcut(value="execution(* com.itheima.spring.demo1.OrderDao.delete(..))") private void pointcut4(){} //前置通知 @Before(value="MyAspectAnno.pointcut2()") public void before(){ System.out.println("前置通知======"); } //后置通知 @AfterReturning(value="MyAspectAnno.pointcut4()", returning="result") public void afterReturning(Object result){ System.out.println("后置通知====="+result); }
//環繞通知 @Around(value="MyAspectAnno.pointcut3()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable{ System.out.println("環繞前增強====="); Object obj = joinPoint.proceed(); System.out.println("環繞后增強====="); return obj; } //異常拋出通知 @AfterThrowing(value="MyAspectAnno.pointcut1()" , throwing="e") public void find(Throwable e ){ System.out.println("異常拋出通知======"+e.getMessage()); } // 最終通知: @After(value="MyAspectAnno.pointcut1()") public void after( ){ System.out.println("最終通知======"); } }