/**
* Spring AOP 基于动态代理和反射完成
*/
interface IEat{
public void eat();
}
class Eat implements IEat{
@Override
public void eat() {
System.out.println("eat");
}
}
interface Dlog{
public void start();
public void end();
}
class Log implements Dlog{
public void start(){
System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"-start");
}
public void end(){
System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"-end");
}
}
//静态代理这里是implements IEat
public class DynamicProxy implements InvocationHandler {
private Object target;//目标对象
private Object proxy;//代理对象
public Object bind(Object target,Object proxy) {
this.target=target;
this.proxy=proxy;
//这个返回的是一个系统创建的代理业务对象,返回的对象关联于IEat
//super.h.invoke(this, m3, null); JVM生成的字节码文件中可以发现是我们传入的this(DynamicProxy)调用的invoke
return Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
Class clazz = this.proxy.getClass();
Method method1 = clazz.getMethod("start");
method1.invoke(this.proxy);
result = method.invoke(this.target);
Method method2 = clazz.getMethod("end");
method2.invoke(this.proxy);
return result;
}
public static void main(String[] args) {
IEat iEat = (IEat) new DynamicProxy().bind(new Eat(),new Log());
iEat.eat();
}
}
总结:spring mvc aop是基于动态代理和反射完成的