JDK 动态代理和 CGLIB 动态代理对比
JDK 动态代理和 CGLIB 动态代理都是实现 Spring AOP 的方式之一。
JDK 动态代理通常用于代理实现了接口的类。它是通过 java.lang.reflect.Proxy
类和 InvocationHandler
接口实现的。
CGLIB 动态代理是一个强大的高性能的代码生成库,它可以为一个类创建子类,重写其方法并添加增强的代码。CGLIB 通常用于代理没有实现接口的类。
下面是使用 JDK 动态代理和 CGLIB 动态代理的简单示例:
JDK 动态代码示例:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JdkDynamicProxyExample {
static class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method invocation: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After method invocation: " + method.getName());
return result;
}
}
interface MyInterface {
void myMethod();
}
static class MyRealClass implements MyInterface {
@Override
public void myMethod() {
System.out.println("Real method execution");
}
}
public static void main(String[] args) {
MyRealClass real = new MyRealClass();
InvocationHandler handler = new MyInvocationHandler(real);
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
MyRealClass.class.getClassLoader(),
new Class[]{MyInterface.class},
handler);
proxy.myMethod();
}
}
CGLIB 动态代码示例:
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibDynamicProxyExample {
static class MyMethodInterceptor implements MethodInterceptor {
private Object target;
public MyMethodInterceptor(Object target) {
this.target = target;
}
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("Before method invocation: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After method invocation: " + method.get
评论已关闭