在spring中是如何实现AOP的

2014-11-23 22:14:46 · 作者: · 浏览: 0

1.在方法开始的时候输出 函数名 开始时间
2.在方法结束的时候输出 函数名 结束时间 以及 方法 花费 的 时间

然后再次贴出我的贴图,表明结果



成功完成。

这时候,也该看看我是如何完成的吧,请注意黑体字的内容

其他代码和上篇相同,这里添加了一个新的类

1.EventHandler.java
========================================================================
package org.dong.core;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Date;

public class EventHandler implements InvocationHandler {

private Object delegate;

public EventHandler(Object delegatec)
{
//把需要代理的物件传进来
this.delegate = delegatec;
}


public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {

Object obj = null;

long startTime = System.currentTimeMillis();

//做之前 我可以加一些代码,这里就是功能实现的地方
Date dt = new Date();
System.err.println(method+"begin"+" @ "+dt.toString());

obj = method.invoke(delegate,args); //嘿修,我XX,代理的过程
//做之后,我也可以加一些代码
dt = new Date();
long endTime = System.currentTimeMillis();

System.err.println(method+"end"+" @ "+
dt.toString()+ "time "+(endTime - startTime)+" ms");
return obj;//把做完的踢出去,嘿嘿


}

}

然后我修改了相应的BeanFactory实现类,来完成我们的功能


package org.dong.core;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;


public class XmlBeanFactory implements BeanFactory {

private String ResPath;

private static DongXmlOp XmlOp;

public XmlBeanFactory(Resource Res) {

ResPath = Res.GetResPath();
XmlOp = new DongXmlOp(ResPath);

}

public Object getBean(String string) {
Bean tmpBean;
tmpBean = XmlOp.GetBeanByID(string);
try {

Class rtnClass = Class.forName(tmpBean.getBeanClass());
//tempBean.getBeanClass()="user" or "userNew" in the DongContext.xml

//好了,在这里我们将实现 AOP,把我们到底干了什么给 print出来 *_*


Object rtnInstance= rtnClass.newInstance();
//这里是最重要的一句话,反射的精髓

//看到这里了么,动态代理被我们包括到了我们的Dong里面,完全没有改动用户代码哦。


InvocationHandler handler = new EventHandler(rtnInstance);

Object rtnInProxy= Proxy.newProxyInstance(
rtnInstance.getClass().getClassLoader(),
rtnInstance.getClass().getInterfaces(),
handler);
//动态代理的实现

//记得我们原来直接就把 rtnInstance 踢出去了么,这次我们代理了以后把代理踢出去了。

return rtnInProxy;


} catch (Exception e) {
System.err.println(e);
}


return tmpBean;
}

}