//切面类 @Aspect public class PreGreetingAspect{ @Before("execution(* greetTo(..))") public void beforeGreeting(){ System.out.println("How are you"); } }
//目标类 @Monitorable public class NaiveWaiter implements Waiter { public void greetTo(String clientName) { System.out.println("NaiveWaiter:greet to "+clientName+"..."); } @NeedTest public void serveTo(String clientName){ System.out.println("NaiveWaiter:serving "+clientName+"..."); } public void smile(String clientName,int times){ System.out.println("NaiveWaiter:smile to "+clientName+ times+"times..."); } }
@Test public void proxy(){ //目标类 Waiter target = new NaiveWaiter(); //代理工厂 AspectJProxyFactory factory = new AspectJProxyFactory(); factory.setTarget(target); //织入 factory.addAspect(PreGreetingAspect.class); Waiter proxy = factory.getProxy(); proxy.greetTo("John"); proxy.serveTo("John"); }
@AspectJ基本语法,spring中可以使用
方法切点:
execution(*greetTo(…))..greetTo方法
@annotation(com.smart.NeddTest).有这种注解的方法。
方法入参切点:
args(com.smart.Waiter).目标类方法入参为waiter
@args(com.smart.Monitorable).目标类方法入参类有@Monitorable注解
目标类切点函数:
within(com.smart.service.*)这个类下面的所有方法都是切点
target(com.smart.waiter).这个类和实现类的所有方法
@within()
@target()
this()
*:
…:
+: