JDK动态代理与CGLIB动态代理

爱⌒轻易说出口 提交于 2020-01-13 08:23:24

JDK动态代理和CGLIB动态代理是SpringAOP非常重要的两个概念,SpringAOP是通过生成目标对象的代理类来实现对目标对象的增强,在说JDK的动态代理之前我们先来回顾一下静态代理:

一、静态代理:

首先定义一个业务接口

public interface ITestService {
    void sayHello();
    String getMsg();
}

然后我们编写一个简单的实现类:

public class TestServiceImpl implements ITestService{
    @Override
    public void sayHello() {
        System.out.println("TestServiceImpl sayHello");
    }
    @Override
    public String getMsg() {
        return "TestServiceImpl Msg";
    }
}

然后我们再编写一个代理类用来代理TestServiceImpl:

public class TestServiceProxy implements ITestService {
    private ITestService target;

    public TestServiceProxy(ITestService testService) {
        this.target = testService;
    }

    @Override
    public void sayHello() {
        System.out.println("sayHello invoke before");
        this.target.sayHello();
        System.out.println("sayHello invoke after");
    }

    @Override
    public String getMsg() {
        System.out.println("getMsg invoke before");
        String result = this.target.getMsg();
        System.out.println("getMsg invoke after");
        return result;
    }
}

最后我们编写一个场景类来模拟使用场景:

public class Client {
    public static void main(String[] args) {
        ITestService testService = new TestServiceProxy(new TestServiceImpl());
        testService.sayHello();
        String msg = testService.getMsg();
        System.out.println(msg);
    }
}

最后输出:

结果很简单,我们通过TestServiceProxy对象实现了对TestServiceImpl的代理,并且这个代理对场景类Clinet是隐藏的,这个就是代理模式。

我们回头看一下这个静态代理的实现方式缺点,我们为了实现对ITestService的实现类的代理,写了一个代理类TestServiceProxy,这个代理类只能代理ITestService的子类,如果需要代理其他的对象,哪怕代理逻辑是一样的,也需要重新编写一个代理类,这样势必会导致类的数量大量增加,最终导致项目十分臃肿,JDK1.3中加入的代理模式就解决了这个问题,让代理类可以代理多个对象,不需要编写重复的代理逻辑。

二、JDK动态代理

JDK动态代理的核心是InvocationHandler接口,首先我们编写一个代理类,注意这个代理类的名字是MyProxy,说明它不再与任何具体的接口建立依赖关系。

public class MyProxy implements InvocationHandler {
    private Object target;
    public MyProxy(Object target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("invoke before");
        Object result = method.invoke(target);
        System.out.println("invoke after");
        return result;
    }
}

接下来通过Proxy.newProxyInstance来生成一个代理对象,此时我们才需要传入被代理的接口,把与被代理对象建立依赖关系的步骤放到了场景类中。

public class Client {
    public static void main(String[] args) {
        // 将Proxy.newProxyInstance生成的代理对象输出到com\sun\proxy目录
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", true);
        MyProxy proxy = new MyProxy(new TestServiceImpl());
        ITestService service = (ITestService) Proxy.newProxyInstance(Client.class.getClassLoader(),
            new Class[]{ITestService.class}, proxy);
        service.sayHello();
        String result = service.getMsg();
        System.out.println(result);
    }
}

输出结果还是一样,JDK动态代理其实就是Proxy.newProxyInstance方法帮我们动态生成了一个代理对象,不需要我们手动去编写了,反编译查看一下生成的动态代理对象:

public final class $Proxy0 extends Proxy implements ITestService {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m0;
    private static Method m4;

    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void sayHello() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String getMsg() throws  {
        try {
            return (String)super.h.invoke(this, m4, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m3 = Class.forName("proxy.ITestService").getMethod("sayHello");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
            m4 = Class.forName("proxy.ITestService").getMethod("getMsg");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

可以看到生成的$Proxy0通过继承Proxy接口来持有InvocationHandler,并且实现了传入的接口,实际调用method的时候其实是调用的InvocationHandler的invoker方法。通过这种方式实现了代理。并且$Proxy0不仅仅代理了getMsg和sayHello方法,还代理了toString,hasCode,equals等默认方法。

可以看到JDK动态代理的优点,MyProxy中实现的代理逻辑可以应用在任何想要代理的业务对象上,JDK的动态代理也是SpringAOP中默认的代理方式。

但是JDK动态代理是通过继承Proxy对象,并实现目标对象的父接口的方式来完成代理的,这种方式也有很大的局限性,如果一个类没有实现接口,那么就不能使用JDK动态代理了,就需要用到CGLIB动态代理了。

三、CGLIB动态代理

CGLIB全称是Code Generation Library,是一个高性能的code生成工具,能够在程序运行期间动态的扩展JAVA类与实现JAVA接口。

我们来看实现方式,首先编写一个业务对象,注意这个对象不再实现任何接口,并且将getMsg方法设置为final类型

public class TestService {
    public void sayHello() {
        System.out.println("TestService sayHello");
    }
    public final String getMsg() {
        return "TestService Msg";
    }
}

CGLIB动态代理的核心是MethodInterceptor接口,我们需要自己编写一个类去实现MethodInterceptor,这个和InvocationHandler相同:

public class MyMethodInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置通知");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("后置通知");
        return result;
    }
}

编写场景类,使用CGLIB生成代理对象:

public class Client {
    public static void main(String[] args) {
        // 将CGLIB生成的class对象存入磁盘
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, ".\\");

        // 创建Enhancer对象,用来生成代理类
        Enhancer enhancer = new Enhancer();
        // 设置被代理对象
        enhancer.setSuperclass(TestService.class);
        // 设置回调接口,就是的代理逻辑
        enhancer.setCallback(new MyMethodInterceptor());
        // 生成代理对象
        TestService testService= (TestService)enhancer.create();

        // 通过代理对象调用目标方法
        testService.sayHello();
    }
}

结果如下:

生成的class类有三个,另外两个是为了生成代理对象服务的:

反编译出来看看:

package proxy;

import java.lang.reflect.Method;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.cglib.core.Signature;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public class TestService$$EnhancerByCGLIB$$6902e37c extends TestService implements Factory {
    private boolean CGLIB$BOUND;
    public static Object CGLIB$FACTORY_DATA;
    private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
    private static final Callback[] CGLIB$STATIC_CALLBACKS;
    private MethodInterceptor CGLIB$CALLBACK_0;
    private static Object CGLIB$CALLBACK_FILTER;
    private static final Method CGLIB$sayHello$0$Method;
    private static final MethodProxy CGLIB$sayHello$0$Proxy;
    private static final Object[] CGLIB$emptyArgs;
    private static final Method CGLIB$equals$1$Method;
    private static final MethodProxy CGLIB$equals$1$Proxy;
    private static final Method CGLIB$toString$2$Method;
    private static final MethodProxy CGLIB$toString$2$Proxy;
    private static final Method CGLIB$hashCode$3$Method;
    private static final MethodProxy CGLIB$hashCode$3$Proxy;
    private static final Method CGLIB$clone$4$Method;
    private static final MethodProxy CGLIB$clone$4$Proxy;

    static void CGLIB$STATICHOOK1() {
        CGLIB$THREAD_CALLBACKS = new ThreadLocal();
        CGLIB$emptyArgs = new Object[0];
        Class var0 = Class.forName("proxy.TestService$$EnhancerByCGLIB$$6902e37c");
        Class var1;
        Method[] var10000 = ReflectUtils.findMethods(new String[]{"equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
        CGLIB$equals$1$Method = var10000[0];
        CGLIB$equals$1$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$1");
        CGLIB$toString$2$Method = var10000[1];
        CGLIB$toString$2$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$2");
        CGLIB$hashCode$3$Method = var10000[2];
        CGLIB$hashCode$3$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$3");
        CGLIB$clone$4$Method = var10000[3];
        CGLIB$clone$4$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$4");
        CGLIB$sayHello$0$Method = ReflectUtils.findMethods(new String[]{"sayHello", "()V"}, (var1 = Class.forName("proxy.TestService")).getDeclaredMethods())[0];
        CGLIB$sayHello$0$Proxy = MethodProxy.create(var1, var0, "()V", "sayHello", "CGLIB$sayHello$0");
    }

    final void CGLIB$sayHello$0() {
        super.sayHello();
    }

    public final void sayHello() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$sayHello$0$Method, CGLIB$emptyArgs, CGLIB$sayHello$0$Proxy);
        } else {
            super.sayHello();
        }
    }

    final boolean CGLIB$equals$1(Object var1) {
        return super.equals(var1);
    }

    public final boolean equals(Object var1) {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            Object var2 = var10000.intercept(this, CGLIB$equals$1$Method, new Object[]{var1}, CGLIB$equals$1$Proxy);
            return var2 == null ? false : (Boolean)var2;
        } else {
            return super.equals(var1);
        }
    }

    final String CGLIB$toString$2() {
        return super.toString();
    }

    public final String toString() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        return var10000 != null ? (String)var10000.intercept(this, CGLIB$toString$2$Method, CGLIB$emptyArgs, CGLIB$toString$2$Proxy) : super.toString();
    }

    final int CGLIB$hashCode$3() {
        return super.hashCode();
    }

    public final int hashCode() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            Object var1 = var10000.intercept(this, CGLIB$hashCode$3$Method, CGLIB$emptyArgs, CGLIB$hashCode$3$Proxy);
            return var1 == null ? 0 : ((Number)var1).intValue();
        } else {
            return super.hashCode();
        }
    }

    final Object CGLIB$clone$4() throws CloneNotSupportedException {
        return super.clone();
    }

    protected final Object clone() throws CloneNotSupportedException {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        return var10000 != null ? var10000.intercept(this, CGLIB$clone$4$Method, CGLIB$emptyArgs, CGLIB$clone$4$Proxy) : super.clone();
    }

    public static MethodProxy CGLIB$findMethodProxy(Signature var0) {
        String var10000 = var0.toString();
        switch(var10000.hashCode()) {
        case -508378822:
            if (var10000.equals("clone()Ljava/lang/Object;")) {
                return CGLIB$clone$4$Proxy;
            }
            break;
        case 1535311470:
            if (var10000.equals("sayHello()V")) {
                return CGLIB$sayHello$0$Proxy;
            }
            break;
        case 1826985398:
            if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
                return CGLIB$equals$1$Proxy;
            }
            break;
        case 1913648695:
            if (var10000.equals("toString()Ljava/lang/String;")) {
                return CGLIB$toString$2$Proxy;
            }
            break;
        case 1984935277:
            if (var10000.equals("hashCode()I")) {
                return CGLIB$hashCode$3$Proxy;
            }
        }

        return null;
    }

    public TestService$$EnhancerByCGLIB$$6902e37c() {
        CGLIB$BIND_CALLBACKS(this);
    }

    public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] var0) {
        CGLIB$THREAD_CALLBACKS.set(var0);
    }

    public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] var0) {
        CGLIB$STATIC_CALLBACKS = var0;
    }

    private static final void CGLIB$BIND_CALLBACKS(Object var0) {
        TestService$$EnhancerByCGLIB$$6902e37c var1 = (TestService$$EnhancerByCGLIB$$6902e37c)var0;
        if (!var1.CGLIB$BOUND) {
            var1.CGLIB$BOUND = true;
            Object var10000 = CGLIB$THREAD_CALLBACKS.get();
            if (var10000 == null) {
                var10000 = CGLIB$STATIC_CALLBACKS;
                if (CGLIB$STATIC_CALLBACKS == null) {
                    return;
                }
            }

            var1.CGLIB$CALLBACK_0 = (MethodInterceptor)((Callback[])var10000)[0];
        }

    }

    public Object newInstance(Callback[] var1) {
        CGLIB$SET_THREAD_CALLBACKS(var1);
        TestService$$EnhancerByCGLIB$$6902e37c var10000 = new TestService$$EnhancerByCGLIB$$6902e37c();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Callback var1) {
        CGLIB$SET_THREAD_CALLBACKS(new Callback[]{var1});
        TestService$$EnhancerByCGLIB$$6902e37c var10000 = new TestService$$EnhancerByCGLIB$$6902e37c();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
        CGLIB$SET_THREAD_CALLBACKS(var3);
        TestService$$EnhancerByCGLIB$$6902e37c var10000 = new TestService$$EnhancerByCGLIB$$6902e37c;
        switch(var1.length) {
        case 0:
            var10000.<init>();
            CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
            return var10000;
        default:
            throw new IllegalArgumentException("Constructor not found");
        }
    }

    public Callback getCallback(int var1) {
        CGLIB$BIND_CALLBACKS(this);
        MethodInterceptor var10000;
        switch(var1) {
        case 0:
            var10000 = this.CGLIB$CALLBACK_0;
            break;
        default:
            var10000 = null;
        }

        return var10000;
    }

    public void setCallback(int var1, Callback var2) {
        switch(var1) {
        case 0:
            this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
        default:
        }
    }

    public Callback[] getCallbacks() {
        CGLIB$BIND_CALLBACKS(this);
        return new Callback[]{this.CGLIB$CALLBACK_0};
    }

    public void setCallbacks(Callback[] var1) {
        this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
    }

    static {
        CGLIB$STATICHOOK1();
    }
}

生成的Class对象是TestService的子类,其中的核心是sayHello方法:

public final void sayHello() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$sayHello$0$Method, CGLIB$emptyArgs, CGLIB$sayHello$0$Proxy);
        } else {
            super.sayHello();
        }
    }

可以看到是调用sayHello方法其实是通过MethodInterceptor的intercept方法来调用的,也就实现了代理逻辑。

以上就是JDK动态代理和CGLIB的动态代理,在SpringAOP中,默认是使用JDK动态代理,当一个类没有父接口时,会改用CBLIB动态代理。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!