AOP实现的底层原理-基于JDK的动态代理实现方法
目标方法
public class Target implements TargetInterFace{
@Override
public void save() {
System.out.println("save is running");
}
}
目标接口
public interface TargetInterFace {
void save ();
}
增强
public class Advice {
public void before(){
System.out.println("前置增强");
}
public void afterReturning(){
System.out.println("后置增强");
}
}
测试类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
//新建目标对象
final Target target = new Target();
//获得增强对象
final Advice advice = new Advice();
TargetInterFace proxy = (TargetInterFace) Proxy.newProxyInstance(
target.getClass().getClassLoader(), //目标对象加载器
target.getClass().getInterfaces(), //目标对象相同的接口字节码对象数组
new InvocationHandler() {
@Override
//调用代理对象的任何方法,实质执行的是invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
advice.before();
Object invoke = method.invoke(target, args);
advice.afterReturning();
return invoke;
}
}
);
//调用动态代理方法
proxy.save();
}
}
总结:
**实现AOP的方法主要有两种:
- JDK动态代理
- cglib动态代理
**
**
本文通过实例详细解析了面向切面编程(AOP)的实现原理,并重点介绍了基于JDK动态代理来实现AOP的具体步骤。通过创建目标接口、目标类及增强类,再利用JDK提供的Proxy类创建动态代理对象,最终实现了方法调用前后增加额外操作的目的。
3403

被折叠的 条评论
为什么被折叠?



