书接上回,上一次我们介绍了spring的ioc,并对它进行了简单的模拟工作,这一次我们模拟一下aop,原理其实很简单,就是利用代理类。下面我们进行代理类的讲解
package com.dingjianlei.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* @auth dingjialei 模拟aop 切面
*/
public class MyinvocationHandler implements InvocationHandler {
private Object target;
/**
* @param o
*/
public void setTarget(Object o) {
this.target = o;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Extend.beforeExtend();
Object result = method.invoke(target, args);
Extend.afterExtend();
return result;
}
}
package com.dingjianlei.aop;
import java.lang.reflect.Proxy;
/**
* @author dingjianlei 代理工厂类获取代理对象static 方法
*/
public class MyProxyFactory {
public static Object getObject(Object target) {
MyinvocationHandler MyinvocationHandler = new MyinvocationHandler();
MyinvocationHandler.setTarget(target);
Object o = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
MyinvocationHandler);
return o;
}
}
package com.dingjianlei.aop;
public class Extend {
public static void beforeExtend(){
System.out.println("前置增强");
}
public static void afterExtend(){
System.out.println("后置增强");
}
}
我们定义一个接口Car,给出它的实现类Aodi,
package com.dingjianlei.aop;
public class Aodi implements Car {
private String name;
public Aodi(String name) {
this.name = name;
}
public String getCarName() {
// TODO Auto-generated method stub
System.out.println("car---name");
return name;
}
}
package com.dingjianlei.aop;
public interface Car {
public String getCarName();
}
package com.dingjianlei.aop;
public class AopTest {
public static void main(String[] args) {
Car car=new Aodi("222");
Car proxyCar = (Car) MyProxyFactory.getObject(car);
proxyCar.getCarName();
}
}
以上就是我们模拟的spring的aop,原理就是我们对一个类进行代理,用它的代理类进行增强,这样我们不需要对原有的类进行拓展。