分类:
2008-10-17 14:26:37
今天在做AspectJ的时间遇到点小问题,看到好多网友在网上问,就写一个例子出来,供大家参考
简单的说如果@args(com.myapp.Test)是表示有且仅有一个入参且入参对象的类标注@Test注解。
如果还不明白的话,看下面的例子,:
先把代码写出来:
任意定义一个空ANNOTATION(注解类)
package cn.kingfengks.aspectJaop.test;
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Monitorable {
}
标记了注解的类
package cn.kingfengks.aspectJaop.test;
@Monitorable //关键 public class NaiveWaiter implements Waiter { public void greetTo(String clientName) { System.out.println("NaiveWaiter:greet to "+clientName+"..."); }
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..."); } }
切面类
package cn.kingfengks.aspectJaop.test;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before;
@Aspect public class PreGreetingAspect { /* * @args test */ @Before("@args(cn.kingfengks.aspectJaop.test.Monitorable)") //标记@Args public void argsSell(){ System.out.println("Test @args successful!"); } }
主函数
public static void main(String[] args) {
String configPath = "cn/kingfengks/aspectJaop/test/applicationContext.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
test------// WaiterManager wm = (WaiterManager)ctx.getBean("waiterManager"); NaiveWaiter waiter3 = new NaiveWaiter(); NaiveWaiter waiter4 = (NaiveWaiter) ctx.getBean("naiveWaiter");//两种方法做对比,前一种没用代理,没有注入切点函数
wm.addNaiveWaiter(waiter3); wm.addWaiter(waiter4);
配置文件
希望你看明白了