AOP的兑现
1.先做一个接口 里有 foo()方法
package com.lily.rules;
public interface IUserDAO {
public void foo();
}
2.在做一个实现接口的类
package com.lily.rules;
public class UserDAOImp implements IUserDAO {
public void foo() {//固定的方法
// TODO Auto-generated method stub
System.out.println("hello first");
}
}
3.做一个测试类
package com.lily.rules;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class MainApplication {
public static void main(String args[]){
ApplicationContext txt = new FileSystemXmlApplicationContext
("D:\\workspace\\FirstSample\\com\\lily\\rules\\applicationContext.xml");
IUserDAO log = (IUserDAO) txt.getBean("businesslogicbean");
log.foo();
}
}
}
4.做一个Before类:固定的类名和实现的接口
package com.lily.rules;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class TracingBeforeAdvice implements MethodBeforeAdvice {
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
// TODO Auto-generated method stub
System.out.println(" hello before");
}
}
5.开始做After类:固定的类名和实现的接口
package com.lily.rules;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class TracingAfterAdvice implements AfterReturningAdvice {
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println("hello after");
}
6.做配置信息 applicationContext.xml文件
<beans></beans>
一个完整的切面操作代码完成了!!
beforeMethod
afterMethod
roundMethod
原Method
调用这个类时先检查代理对象,判断是否有aop方法,有则根据先后顺序,执行aop方法。
如果没有,直接执行方法。