代码如下:
package ch2.test; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Aspect; @Aspect public class Audience { //表演之前:观点手机 @Before("execution(** ch2.test.Performance.perform(..))") public void silenceCellPhones() { System.out.println("silenCellPhones"); } //表演之前:就座 @Before("execution(** ch2.test.Performance.perform(..))") public void takingSeats() { System.out.println("take seats"); } //表演之后:鼓掌 @AfterReturning("excuttion(** ch2.test.Performance.perform(..))") public void applause() { System.out.println("clap clap clap !!!"); } //表演失败:退票 @AfterThrowing("execution(** ch2.test.Performance.perform(..))") public void demandRefund() { System.out.println("demanding a refund"); } }
2.Pointcut
org.aspectj.lang.annotation.Pointcut;
1 package ch2.test; 2 3 import org.aspectj.lang.annotation.AfterReturning; 4 import org.aspectj.lang.annotation.AfterThrowing; 5 import org.aspectj.lang.annotation.Aspect; 6 import org.aspectj.lang.annotation.Before; 7 import org.aspectj.lang.annotation.Pointcut; 8 9 @Aspect 10 public class Audience2 { 11 12 13 //定义命名的切点 14 @Pointcut("execution(** ch2.test.Performance.perform(..))") 15 public void Performance(){} 16 17 //表演开始之前:关闭手机 18 @Before("Performance()") 19 public void silenCellPhones() 20 { 21 System.out.println("silen cell phones"); 22 } 23 24 //表演开始之前:入座 25 @Before("Performance()") 26 public void takingSeats() 27 { 28 System.out.println("take seats"); 29 } 30 31 //表演开始之后:鼓掌 32 @AfterReturning("Performance()") 33 public void applause() 34 { 35 System.out.println("clap clap clap"); 36 } 37 38 //表演结束之后:表演失败退票 39 @AfterThrowing("Performance()") 40 public void demandRefund() 41 { 42 System.out.println("demand refund"); 43 } 44 45 }