[01][01][07] 代理模式详解

[TOC]

1. 定义

代理模式是指为其他对象提供一种代理,以控制对这个对象的访问

代理对象在客服端和目标对象之间起到中介作用

2. 适用场景

  • 保护目标对象
  • 增强目标对象

3. 分类

  • 静态代理
  • JDK 动态代理
  • CGLIB 动态代理

3.1 静态代理

3.1.1 代码实现

  • 定义被代理类
public interface Person {
    /**
     * 相亲
     */
    void findLove();
}
public class Son implements Person {
    @Override
    public void findLove() {
        System.out.println("寻找伴侣要求: 肤白貌美大长腿");
    }
}
  • 代理类
public class Father implements Person {
    private Son son;

    public Father(Son son) {
        this.son = son;
    }

    @Override
    public void findLove() {
        this.before();
        this.son.findLove();
        this.after();
    }

    /**
     * 增强目标对象
     * 执行之前
     */
    private void before(){
        System.out.println("父亲正在帮儿子物色对象");
    }

    /**
     * 增强目标对象
     * 执行之后
     */
    private void after(){
        System.out.println("双方父母同意,确定关系");
    }
}
  • 测试类
public class FatherProxyTest {
    public static void main(String[] args) {
        Father father = new Father(new Son());
        father.findLove();
    }
}
  • 运行结果


    image

3.1.2 总结

被代理类 Son 当前只有 findLove 需求,后期增加 findJob 等更多的需求,Father 也要增加对应的代码,不符合开闭原则

代理类与被代理类中间存在联系,代理类不能对所有的类服务

3.1.3 扩展--分库分表

  • Order 订单实体
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
    private Object orderInfo;
    private Long createTime;
    private String id;
}
  • OrderDao 持久层
public class OrderDao {
    public int insert(Order order) {
        System.out.println("OrderDao 创建 Order 成功!");
        return 1;
    }
}
  • IOrderService 接口
public interface IOrderService {
    int createOrder(Order order);
}
  • OrderService 实现类
public class OrderService implements IOrderService {
    private OrderDao orderDao;

    public OrderService() {
        //如果使用 Spring 应该是自动注入的
        //我们为了使用方便,在构造方法中将 orderDao 直接初始化了
        orderDao = new OrderDao();
    }

    @Override
    public int createOrder(Order order) {
        System.out.println("OrderService 调用 orderDao 创建订单");
        return orderDao.insert(order);
    }
}
  • ThreadLocal 的单例实现 DynamicDataSourceEntry 类

接下来使用静态代理,主要完成的功能是,根据订单创建时间自动按年进行分库.根据开闭原则,原来写好的逻辑我们不去修改,通过代理对象来完成.先创建数据源路由对象,我们使用 ThreadLocal 的单例实现 DynamicDataSourceEntry 类

/**
 * 动态切换数据源
 */
public class DynamicDataSourceEntry {
    // 默认数据源
    public final static String DEFAULT_SOURCE = null;

    private final static ThreadLocal local = new ThreadLocal();

    private DynamicDataSourceEntry() {
    }

    /**
     * 清空数据源
     */
    public static void clear() {
        local.remove();
    }

    /**
     * 获取当前正在使用的数据源名字
     */
    public static String get() {
        return local.get();
    }

    /**
     * 还原当前切面的数据源
     */
    public static void restore() {
        local.set(DEFAULT_SOURCE);
    }

    /**
     * 设置已知名字的数据源
     */
    public static void set(String source) {
        local.set(source);
    }

    /**
     * 根据年份动态设置数据源
     */
    public static void set(int year) {
        local.set("DB_" + year);
    }
}
  • 创建切换数据源的代理 OrderServiceSaticProxy 类
public class OrderServiceStaticProxy implements IOrderService {

    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");

    private IOrderService orderService;

    public OrderServiceStaticProxy(IOrderService orderService) {
        this.orderService = orderService;
    }

    public int createOrder(Order order) {
        before();

        Long time = order.getCreateTime();
        Integer dbRouter = Integer.valueOf(yearFormat.format(new Date(time)));
        System.out.println("静态代理类自动分配到[DB_" + dbRouter + "]数据源处理数据");

        DynamicDataSourceEntry.set(dbRouter);
        orderService.createOrder(order);

        after();
        return 0;
    }

    private void before() {
        System.out.println("Proxy before method.");
    }

    private void after() {
        System.out.println("Proxy after method.");
    }
}
  • 测试代码
public class OrderTest {
    public static void main(String[] args) {
        try {
            Order order = new Order();

            order.setCreateTime(System.currentTimeMillis());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            Date date = sdf.parse("2017/02/01");
            order.setCreateTime(date.getTime());

            IOrderService orderService = new OrderServiceStaticProxy(new OrderService());

            orderService.createOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 运行结果


    image

3.2 JDK 动态代理

3.2.1 实现原理

  • 拿到被代理类的引用,并且获取它的所有接口(反射获取)
  • JDKProxy 类重新生成一个新的类,实现了被代理类所有接口的方法
  • 动态生成 java 代码,把增强逻辑加入到新生成代码中
  • 编译生成新的 java 代码的 class 文件
  • 加载并重新运行新的 class,得到的类就是全新类

3.2.2 代码实现

  • 被代理类
public interface Person {
    /**
     * 相亲
     */
    void findLove();
}
public class Girl implements Person {

    @Override
    public void findLove() {
        System.out.println("寻找对象要求:");
        System.out.println("身高 180");
        System.out.println("有钱");
        System.out.println("有六块腹肌");
    }
}
  • 代理类
public class JDKMeipo implements InvocationHandler {

    private Person person;

    public Object getInstance(Person person) {
        this.person = person;
        Class clazz = this.person.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object object = method.invoke(this.person, args);
        before();
        return object;
    }

    /**
     * 增强目标对象
     * 执行之前
     */
    private void before(){
        System.out.println("我是媒婆,已经收到你的诉求");
        System.out.println("正在物色对象");
    }

    /**
     * 增强目标对象
     * 执行之后
     */
    private void after(){
        System.out.println("相亲完成,确认双方意见");
    }
}
  • 测试类
public class JDKProxyTest {
    public static void main(String[] args) {
        Person person = (Person) new JDKMeipo().getInstance(new Girl());
        person.findLove();
    }
}
  • 运行结果


    image

3.2.3 总结

  • 被代理类 Girl 在 findLove 功能的基础上增加其他需求,代理类 JDKMeiPo 不需要修改代码
  • 代理类 JDKMeiPo 不仅可以代理 Girl 类,也可以代理其他类

3.2.4 拓展

再来看数据源动态路由业务,帮助小伙伴们对动态代理加深一下印象.创建动态代理的类 OrderServiceDynamicProxy,代码如下

public class OrderServiceDynamicProxy implements InvocationHandler {
    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");

    private Object target;

    public Object getInstance(Object target){
        this.target = target;
        Class clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(args[0]);

        Object object = method.invoke(target,args);

        after();
        return object;
    }

    private void before(Object target){
        try {
            System.out.println("Proxy before method.");
            Long time = (Long) target.getClass().getMethod("getCreateTime").invoke(target);
            Integer dbRouter = Integer.valueOf(yearFormat.format(new Date(time)));
            System.out.println("静态代理类自动分配到【DB_" + dbRouter + "】数据源处理数据。");
            DynamicDataSourceEntry.set(dbRouter);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void after(){
        System.out.println("Proxy after method.");
    }
}

动态代理实现之后,我们不仅能实现 Order 的数据源动态路由,还可以实现其他任何类的数据源路由.当然,有比较重要的约定,必须要求实现 getCreateTime()方法,因为路由规则是根据时间来运算的.当然,我们可以通过接口规范来达到约束的目的

4. 自己实现 JDK 动态代理

4.1 JDK 动态代理实现步骤

不仅知其然,还得知其所以然,既然 JDKProxy 功能如此强大,那么它是如何实现的呢?
我们现在来探究一下原理,并模仿 JDKProxy 自己动手写一个属于自己的动态代理
我们都知道 JDKProxy 采用字节重组,重新生的对象来替代原始的对象以达到动态代理的目的

JDKProxy 生成对象的步骤如下:

  • 拿到被代理类的引用,并且获取它的所有接口(反射获取)
  • JDKProxy 类重新生成一个新的类,实现了被代理类所有接口的方法
  • 动态生成 java 代码,把增强逻辑加入到新生成代码中
  • 编译生成新的 java 代码的 class 文件
  • 加载并重新运行新的 class,得到的类就是全新类

以上这个过程就叫字节码重组.JDK 中有一个规范,在 ClassPath 下只要是$开头的 class 文件一般都是自动生成的.那么我们有没有办法看到代替后的对象的真容呢?
做一个这样测试,我们从内存中的对象字节码通过文件流输出到一个新的 class 文件,然后利用反编译工具查看 class 的源代码

4.2 jdk 动态代理原理解析

  • 在代理类 JDKMeipo 中传入 Gir 类Personperson=(Person)newJDKMeipo().getInstance(newGirl());,得到 Person 类是一个全新的类$Proxy0

  • $Proxy0这个对象输出到文件$Proxy0.class中,可以看到这个$Proxy类的代码

image
public class JDKProxyTest {
    public static void main(String[] args) {
        Person person = (Person) new JDKMeipo().getInstance(new Girl());
        person.findLove();

        byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class[]{Person.class});

        try (FileOutputStream fileOutputStream = new FileOutputStream("./proxy/$Proxy0.class")) {
            fileOutputStream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

可以看到Methodm3对应就是 Girl 类中的 findLove 方法

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import com.zhunongyun.toalibaba.designpatterns.proxy.Person;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

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

    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 findLove() 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);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m3 = Class.forName("com.zhunongyun.toalibaba.designpatterns.proxy.Person").getMethod("findLove");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

我们发现$Proxy0 继承了 Proxy 类,同时还实现了我们的 Person 接口,而且重写了 findLove()等方法.而且在静态块中用反射查找到了目标对象的所有方法,而且保存了所有方法的引用,在重写的方法用反射调用目标对象的方法.
小伙伴们此时一定在好奇,这些代码是哪里来的呢?其实是 JDK 帮我们自动生成的.现在我们不依赖 JDK 自己来动态生成源代码,动态完成编译,然后替代目标对象并执行

4.3 高仿真 JDKProxy 手写实现

  • 1.被代理类
public class Girl implements Person {

    @Override
    public void findLove() {
        System.out.println("寻找对象要求:");
        System.out.println("身高 180");
        System.out.println("有钱");
        System.out.println("有六块腹肌");
    }
}
  • 2.代理类
public class MyMeipo implements MyInvocationHandler {

    private Person person;

    public Object getInstance(Person person) {
        this.person = person;
        Class clazz = this.person.getClass();
        return MyProxy.newProxyInstance(new MyClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        Object object = null;
        try {
            before();
            object = method.invoke(this.person, args);
            after();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * 增强目标对象
     * 执行之前
     */
    private void before(){
        System.out.println("我是媒婆,已经收到你的诉求");
        System.out.println("正在物色对象");
    }

    /**
     * 增强目标对象
     * 执行之后
     */
    private void after(){
        System.out.println("相亲完成,确认双方意见");
    }
}
  • 3.自定义类加载器 ClassLoader
public class MyClassLoader extends ClassLoader {

    private File classPathFile;

    public MyClassLoader() {
        String classPath = MyClassLoader.class.getResource("").getPath();
        classPathFile = new File(classPath);
    }

    @Override
    public Class findClass(String name) throws ClassNotFoundException {
        String className = MyClassLoader.class.getPackage().getName() + "." +name;
        if (classPathFile != null) {
            File file = new File(classPathFile, name + ".class");

            try (FileInputStream fileInputStream = new FileInputStream(file);
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) {
                byte[] buff = new byte[1024];
                int len;
                while((len=fileInputStream.read(buff))!=-1){
                    outputStream.write(buff, 0, len);
                }
                return defineClass(className, outputStream.toByteArray(), 0, outputStream.size());
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
  • 4.自定义 InvacationHandler
public interface MyInvocationHandler {

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}
  • 5.自定义代理类 Proxy
public class MyProxy {

    public static final String LN = "\r\n";

    public static Object newProxyInstance(MyClassLoader myClassLoader, Class[] interfaces, MyInvocationHandler h) {
        try{
            // 1 动态生成 java 源码
            String src = generateSrc(interfaces);

            // 2 将源码输出到 java 文件中
            String filePath = MyProxy.class.getResource("").getPath();
            File f = new File(filePath + "$Proxy0.java");
            FileWriter fw = new FileWriter(f);
            fw.write(src);
            fw.flush();
            fw.close();

            //3、将 java 文件编译成 class 文件
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager manage = compiler.getStandardFileManager(null,null,null);
            Iterable iterable = manage.getJavaFileObjects(f);

            JavaCompiler.CompilationTask task = compiler.getTask(null,manage,null,null,null,iterable);
            task.call();
            manage.close();

            //4、将 class 加载进 jvm
            Class proxyClass=myClassLoader.findClass("$Proxy0");
            f.delete();

            //5、返回代理类对象
            Constructor constructor = proxyClass.getConstructor(MyInvocationHandler.class);
            return constructor.newInstance(h);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private static String generateSrc(Class[] interfaces) {
        // TODO Auto-generated method stub
        StringBuffer sb = new StringBuffer();
        sb.append("package com.zhunongyun.toalibaba.designpatterns.proxy.myproxy;").append(LN);
        sb.append("import java.lang.reflect.Method;").append(LN);
        sb.append("public class $Proxy0 implements " + interfaces[0].getName() + "{").append(LN);
        sb.append("private MyInvocationHandler h;").append(LN);
        sb.append("public $Proxy0(MyInvocationHandler h) { ").append(LN);
        sb.append("this.h = h;").append(LN);
        sb.append("}").append(LN);
        for (Method m : interfaces[0].getMethods()) {
            sb.append("public " + m.getReturnType().getName() + " " + m.getName() + "() {").append(LN);
            sb.append("try{").append(LN);
            sb.append("Method m = " + interfaces[0].getName() + ".class.getMethod(\"" + m.getName() + "\",new Class[]{});").append(LN);
            sb.append("this.h.invoke(this,m,null);").append(LN);
            sb.append("}catch(Throwable e){").append(LN);
            sb.append("e.printStackTrace();").append(LN);
            sb.append("}").append(LN);
            sb.append("}").append(LN);
        }
        sb.append("}").append(LN);
        return sb.toString();
    }
}
  • 6.测试类
public class MyProxyTest {
    public static void main(String[] args) {
        Person person = (Person) new MyMeipo().getInstance(new Girl());
        person.findLove();
    }
}

5. CGlib 动态代理

  • CGlib 通过继承被代理类,并覆盖被代理类的方法
  • CGlib 可以代理任意一个普通的类,没有任何要求
  • CGlib 生成代理逻辑更加复杂,调用效率更高,生成一个包含了所有的逻辑的 FastClass,不再需要反射调用
  • CGlib 代理有坑,不能代理 final 方法

5.1 代码实现

  • 1.被代理类
public class NewGirl {

    public void findLove() {
        System.out.println("寻找对象要求:");
        System.out.println("身高 180");
        System.out.println("有钱");
        System.out.println("有六块腹肌");
    }
}
  • 2.CGLib 代理类
public class CGlibMeipo implements MethodInterceptor {

    public Object getInstance(Class clazz) throws Exception {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object object = methodProxy.invokeSuper(o, objects);
        after();
        return object;
    }

    /**
     * 增强目标对象
     * 执行之前
     */
    private void before(){
        System.out.println("我是媒婆,已经收到你的诉求");
        System.out.println("正在物色对象");
    }

    /**
     * 增强目标对象
     * 执行之后
     */
    private void after(){
        System.out.println("相亲完成,确认双方意见");
    }
}
  • 3.测试类
public class CGlibProxyTest {
    public static void main(String[] args) {
        // 把 CGlib 生成的代码输出到文件中
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, CGlibProxyTest.class.getResource("").getPath());

        try {
            NewGirl newGirl = (NewGirl) new CGlibMeipo().getInstance(NewGirl.class);
            newGirl.findLove();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

CGLib 代理的目标对象不需要实现任何接口,它是通过动态继承目标对象实现的动态代理

5.2 CGlib 工作原理分析

在 CGlib 代理测试类中输出生成的代码到磁盘文件,生成了以下三个 class 文件

  • NewGirl2a25c1b42393400d.class
  • NewGirl2a25c1b4.class
  • NewGirl1cf5df8b.class

NewGirl2a25c1b4.class 是 CGLib 生成的代理类,继承了 NewGirl 类

反编译这三个 class 文件详情如下

重写了 NewGirl 类的所有方法,我们通过代理类的源码可以看到,代理类会获得所有在父类继承来的方法,并且会有 MethodProxy 与之对应,比如 MethodCGLIB0findLoveProxy;这些方法在代理类的 findLove()中都有调用

  • 1.NewGirl$$EnhancerByCGLIB$$2a25c1b4.class
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.zhunongyun.toalibaba.designpatterns.proxy.cglibproxy;

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 NewGirl$$EnhancerByCGLIB$$2a25c1b4 extends NewGirl 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$findLove$0$Method;
    private static final MethodProxy CGLIB$findLove$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("com.zhunongyun.toalibaba.designpatterns.proxy.cglibproxy.NewGirl$$EnhancerByCGLIB$$2a25c1b4");
        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$findLove$0$Method = ReflectUtils.findMethods(new String[]{"findLove", "()V"}, (var1 = Class.forName("com.zhunongyun.toalibaba.designpatterns.proxy.cglibproxy.NewGirl")).getDeclaredMethods())[0];
        CGLIB$findLove$0$Proxy = MethodProxy.create(var1, var0, "()V", "findLove", "CGLIB$findLove$0");
    }

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

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

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

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

    public final boolean equals(Object var1) {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == 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 (var10000 == 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 (var10000 == 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 (var10000 == 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 1192015562:
            if (var10000.equals("findLove()V")) {
                return CGLIB$findLove$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 NewGirl$$EnhancerByCGLIB$$2a25c1b4() {
        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) {
        NewGirl$$EnhancerByCGLIB$$2a25c1b4 var1 = (NewGirl$$EnhancerByCGLIB$$2a25c1b4)var0;
        if (!var1.CGLIB$BOUND) {
            var1.CGLIB$BOUND = true;
            Object var10000 = CGLIB$THREAD_CALLBACKS.get();
            if (var10000 == null) {
                var10000 = CGLIB$STATIC_CALLBACKS;
                if (var10000 == null) {
                    return;
                }
            }

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

    }

    public Object newInstance(Callback[] var1) {
        CGLIB$SET_THREAD_CALLBACKS(var1);
        NewGirl$$EnhancerByCGLIB$$2a25c1b4 var10000 = new NewGirl$$EnhancerByCGLIB$$2a25c1b4();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Callback var1) {
        CGLIB$SET_THREAD_CALLBACKS(new Callback[]{var1});
        NewGirl$$EnhancerByCGLIB$$2a25c1b4 var10000 = new NewGirl$$EnhancerByCGLIB$$2a25c1b4();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
        CGLIB$SET_THREAD_CALLBACKS(var3);
        NewGirl$$EnhancerByCGLIB$$2a25c1b4 var10000 = new NewGirl$$EnhancerByCGLIB$$2a25c1b4;
        switch(var1.length) {
        case 0:
            var10000.();
            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();
    }
}
  • 2.NewGirl$$EnhancerByCGLIB$$2a25c1b4$$FastClassByCGLIB$$2393400d.class
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.zhunongyun.toalibaba.designpatterns.proxy.cglibproxy;

import com.zhunongyun.toalibaba.designpatterns.proxy.cglibproxy.NewGirl..EnhancerByCGLIB..2a25c1b4;
import java.lang.reflect.InvocationTargetException;
import org.springframework.cglib.core.Signature;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.reflect.FastClass;

public class NewGirl$$EnhancerByCGLIB$$2a25c1b4$$FastClassByCGLIB$$2393400d extends FastClass {
    public NewGirl$$EnhancerByCGLIB$$2a25c1b4$$FastClassByCGLIB$$2393400d(Class var1) {
        super(var1);
    }

    public int getIndex(Signature var1) {
        String var10000 = var1.toString();
        switch(var10000.hashCode()) {
        case -1882565338:
            if (var10000.equals("CGLIB$equals$1(Ljava/lang/Object;)Z")) {
                return 17;
            }
            break;
        case -1870561232:
            if (var10000.equals("CGLIB$findMethodProxy(Lorg/springframework/cglib/core/Signature;)Lorg/springframework/cglib/proxy/MethodProxy;")) {
                return 14;
            }
            break;
        case -1745842178:
            if (var10000.equals("setCallbacks([Lorg/springframework/cglib/proxy/Callback;)V")) {
                return 9;
            }
            break;
        case -1641413109:
            if (var10000.equals("newInstance([Lorg/springframework/cglib/proxy/Callback;)Ljava/lang/Object;")) {
                return 4;
            }
            break;
        case -1457535688:
            if (var10000.equals("CGLIB$STATICHOOK1()V")) {
                return 15;
            }
            break;
        case -1411842725:
            if (var10000.equals("CGLIB$hashCode$3()I")) {
                return 19;
            }
            break;
        case -1034266769:
            if (var10000.equals("CGLIB$SET_STATIC_CALLBACKS([Lorg/springframework/cglib/proxy/Callback;)V")) {
                return 10;
            }
            break;
        case -1025895669:
            if (var10000.equals("CGLIB$SET_THREAD_CALLBACKS([Lorg/springframework/cglib/proxy/Callback;)V")) {
                return 11;
            }
            break;
        case -988317324:
            if (var10000.equals("newInstance([Ljava/lang/Class;[Ljava/lang/Object;[Lorg/springframework/cglib/proxy/Callback;)Ljava/lang/Object;")) {
                return 5;
            }
            break;
        case -508378822:
            if (var10000.equals("clone()Ljava/lang/Object;")) {
                return 3;
            }
            break;
        case 610042816:
            if (var10000.equals("newInstance(Lorg/springframework/cglib/proxy/Callback;)Ljava/lang/Object;")) {
                return 6;
            }
            break;
        case 1096387995:
            if (var10000.equals("CGLIB$findLove$0()V")) {
                return 16;
            }
            break;
        case 1132856532:
            if (var10000.equals("getCallbacks()[Lorg/springframework/cglib/proxy/Callback;")) {
                return 13;
            }
            break;
        case 1192015562:
            if (var10000.equals("findLove()V")) {
                return 7;
            }
            break;
        case 1246779367:
            if (var10000.equals("setCallback(ILorg/springframework/cglib/proxy/Callback;)V")) {
                return 8;
            }
            break;
        case 1306468936:
            if (var10000.equals("CGLIB$toString$2()Ljava/lang/String;")) {
                return 18;
            }
            break;
        case 1364367423:
            if (var10000.equals("getCallback(I)Lorg/springframework/cglib/proxy/Callback;")) {
                return 12;
            }
            break;
        case 1800494055:
            if (var10000.equals("CGLIB$clone$4()Ljava/lang/Object;")) {
                return 20;
            }
            break;
        case 1826985398:
            if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
                return 0;
            }
            break;
        case 1913648695:
            if (var10000.equals("toString()Ljava/lang/String;")) {
                return 1;
            }
            break;
        case 1984935277:
            if (var10000.equals("hashCode()I")) {
                return 2;
            }
        }

        return -1;
    }

    public int getIndex(String var1, Class[] var2) {
        switch(var1.hashCode()) {
        case -1776922004:
            if (var1.equals("toString")) {
                switch(var2.length) {
                case 0:
                    return 1;
                }
            }
            break;
        case -1295482945:
            if (var1.equals("equals")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("java.lang.Object")) {
                        return 0;
                    }
                }
            }
            break;
        case -1053468136:
            if (var1.equals("getCallbacks")) {
                switch(var2.length) {
                case 0:
                    return 13;
                }
            }
            break;
        case -679433013:
            if (var1.equals("findLove")) {
                switch(var2.length) {
                case 0:
                    return 7;
                }
            }
            break;
        case -331698278:
            if (var1.equals("CGLIB$findLove$0")) {
                switch(var2.length) {
                case 0:
                    return 16;
                }
            }
            break;
        case -124978609:
            if (var1.equals("CGLIB$equals$1")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("java.lang.Object")) {
                        return 17;
                    }
                }
            }
            break;
        case -60403779:
            if (var1.equals("CGLIB$SET_STATIC_CALLBACKS")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("[Lorg.springframework.cglib.proxy.Callback;")) {
                        return 10;
                    }
                }
            }
            break;
        case -29025555:
            if (var1.equals("CGLIB$hashCode$3")) {
                switch(var2.length) {
                case 0:
                    return 19;
                }
            }
            break;
        case 85179481:
            if (var1.equals("CGLIB$SET_THREAD_CALLBACKS")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("[Lorg.springframework.cglib.proxy.Callback;")) {
                        return 11;
                    }
                }
            }
            break;
        case 94756189:
            if (var1.equals("clone")) {
                switch(var2.length) {
                case 0:
                    return 3;
                }
            }
            break;
        case 147696667:
            if (var1.equals("hashCode")) {
                switch(var2.length) {
                case 0:
                    return 2;
                }
            }
            break;
        case 161998109:
            if (var1.equals("CGLIB$STATICHOOK1")) {
                switch(var2.length) {
                case 0:
                    return 15;
                }
            }
            break;
        case 495524492:
            if (var1.equals("setCallbacks")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("[Lorg.springframework.cglib.proxy.Callback;")) {
                        return 9;
                    }
                }
            }
            break;
        case 1154623345:
            if (var1.equals("CGLIB$findMethodProxy")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("org.springframework.cglib.core.Signature")) {
                        return 14;
                    }
                }
            }
            break;
        case 1543336189:
            if (var1.equals("CGLIB$toString$2")) {
                switch(var2.length) {
                case 0:
                    return 18;
                }
            }
            break;
        case 1811874389:
            if (var1.equals("newInstance")) {
                switch(var2.length) {
                case 1:
                    String var10001 = var2[0].getName();
                    switch(var10001.hashCode()) {
                    case -1997738671:
                        if (var10001.equals("[Lorg.springframework.cglib.proxy.Callback;")) {
                            return 4;
                        }
                        break;
                    case 1364160985:
                        if (var10001.equals("org.springframework.cglib.proxy.Callback")) {
                            return 6;
                        }
                    }
                case 2:
                default:
                    break;
                case 3:
                    if (var2[0].getName().equals("[Ljava.lang.Class;") && var2[1].getName().equals("[Ljava.lang.Object;") && var2[2].getName().equals("[Lorg.springframework.cglib.proxy.Callback;")) {
                        return 5;
                    }
                }
            }
            break;
        case 1817099975:
            if (var1.equals("setCallback")) {
                switch(var2.length) {
                case 2:
                    if (var2[0].getName().equals("int") && var2[1].getName().equals("org.springframework.cglib.proxy.Callback")) {
                        return 8;
                    }
                }
            }
            break;
        case 1905679803:
            if (var1.equals("getCallback")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("int")) {
                        return 12;
                    }
                }
            }
            break;
        case 1951977610:
            if (var1.equals("CGLIB$clone$4")) {
                switch(var2.length) {
                case 0:
                    return 20;
                }
            }
        }

        return -1;
    }

    public int getIndex(Class[] var1) {
        switch(var1.length) {
        case 0:
            return 0;
        default:
            return -1;
        }
    }

    public Object invoke(int var1, Object var2, Object[] var3) throws InvocationTargetException {
        2a25c1b4 var10000 = (2a25c1b4)var2;
        int var10001 = var1;

        try {
            switch(var10001) {
            case 0:
                return new Boolean(var10000.equals(var3[0]));
            case 1:
                return var10000.toString();
            case 2:
                return new Integer(var10000.hashCode());
            case 3:
                return var10000.clone();
            case 4:
                return var10000.newInstance((Callback[])var3[0]);
            case 5:
                return var10000.newInstance((Class[])var3[0], (Object[])var3[1], (Callback[])var3[2]);
            case 6:
                return var10000.newInstance((Callback)var3[0]);
            case 7:
                var10000.findLove();
                return null;
            case 8:
                var10000.setCallback(((Number)var3[0]).intValue(), (Callback)var3[1]);
                return null;
            case 9:
                var10000.setCallbacks((Callback[])var3[0]);
                return null;
            case 10:
                2a25c1b4.CGLIB$SET_STATIC_CALLBACKS((Callback[])var3[0]);
                return null;
            case 11:
                2a25c1b4.CGLIB$SET_THREAD_CALLBACKS((Callback[])var3[0]);
                return null;
            case 12:
                return var10000.getCallback(((Number)var3[0]).intValue());
            case 13:
                return var10000.getCallbacks();
            case 14:
                return 2a25c1b4.CGLIB$findMethodProxy((Signature)var3[0]);
            case 15:
                2a25c1b4.CGLIB$STATICHOOK1();
                return null;
            case 16:
                var10000.CGLIB$findLove$0();
                return null;
            case 17:
                return new Boolean(var10000.CGLIB$equals$1(var3[0]));
            case 18:
                return var10000.CGLIB$toString$2();
            case 19:
                return new Integer(var10000.CGLIB$hashCode$3());
            case 20:
                return var10000.CGLIB$clone$4();
            }
        } catch (Throwable var4) {
            throw new InvocationTargetException(var4);
        }

        throw new IllegalArgumentException("Cannot find matching method/constructor");
    }

    public Object newInstance(int var1, Object[] var2) throws InvocationTargetException {
        2a25c1b4 var10000 = new 2a25c1b4;
        2a25c1b4 var10001 = var10000;
        int var10002 = var1;

        try {
            switch(var10002) {
            case 0:
                var10001.();
                return var10000;
            }
        } catch (Throwable var3) {
            throw new InvocationTargetException(var3);
        }

        throw new IllegalArgumentException("Cannot find matching method/constructor");
    }

    public int getMaxIndex() {
        return 20;
    }
}
  • 3.NewGirl$$FastClassByCGLIB$$1cf5df8b.class
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.zhunongyun.toalibaba.designpatterns.proxy.cglibproxy;

import java.lang.reflect.InvocationTargetException;
import org.springframework.cglib.core.Signature;
import org.springframework.cglib.reflect.FastClass;

public class NewGirl$$FastClassByCGLIB$$1cf5df8b extends FastClass {
    public NewGirl$$FastClassByCGLIB$$1cf5df8b(Class var1) {
        super(var1);
    }

    public int getIndex(Signature var1) {
        String var10000 = var1.toString();
        switch(var10000.hashCode()) {
        case 1192015562:
            if (var10000.equals("findLove()V")) {
                return 0;
            }
            break;
        case 1826985398:
            if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
                return 1;
            }
            break;
        case 1913648695:
            if (var10000.equals("toString()Ljava/lang/String;")) {
                return 2;
            }
            break;
        case 1984935277:
            if (var10000.equals("hashCode()I")) {
                return 3;
            }
        }

        return -1;
    }

    public int getIndex(String var1, Class[] var2) {
        switch(var1.hashCode()) {
        case -1776922004:
            if (var1.equals("toString")) {
                switch(var2.length) {
                case 0:
                    return 2;
                }
            }
            break;
        case -1295482945:
            if (var1.equals("equals")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("java.lang.Object")) {
                        return 1;
                    }
                }
            }
            break;
        case -679433013:
            if (var1.equals("findLove")) {
                switch(var2.length) {
                case 0:
                    return 0;
                }
            }
            break;
        case 147696667:
            if (var1.equals("hashCode")) {
                switch(var2.length) {
                case 0:
                    return 3;
                }
            }
        }

        return -1;
    }

    public int getIndex(Class[] var1) {
        switch(var1.length) {
        case 0:
            return 0;
        default:
            return -1;
        }
    }

    public Object invoke(int var1, Object var2, Object[] var3) throws InvocationTargetException {
        NewGirl var10000 = (NewGirl)var2;
        int var10001 = var1;

        try {
            switch(var10001) {
            case 0:
                var10000.findLove();
                return null;
            case 1:
                return new Boolean(var10000.equals(var3[0]));
            case 2:
                return var10000.toString();
            case 3:
                return new Integer(var10000.hashCode());
            }
        } catch (Throwable var4) {
            throw new InvocationTargetException(var4);
        }

        throw new IllegalArgumentException("Cannot find matching method/constructor");
    }

    public Object newInstance(int var1, Object[] var2) throws InvocationTargetException {
        NewGirl var10000 = new NewGirl;
        NewGirl var10001 = var10000;
        int var10002 = var1;

        try {
            switch(var10002) {
            case 0:
                var10001.();
                return var10000;
            }
        } catch (Throwable var3) {
            throw new InvocationTargetException(var3);
        }

        throw new IllegalArgumentException("Cannot find matching method/constructor");
    }

    public int getMaxIndex() {
        return 3;
    }
}

重写了 NewGirl 类的所有方法,我们通过代理类的源码可以看到,代理类会获得所有在父类继承来的方法,并且会有 MethodProxy 与之对应,比如 MethodCGLIB0findLoveProxy;这些方法在代理类的 findLove()中都有调用

//代理方法(methodProxy.invokeSuper 会调用)
final void CGLIB$findLove$0()
{
    super.findLove();
}

//被代理方法(methodProxy.invoke 会调用,这就是为什么在拦截器中调用 methodProxy.invoke 会死循环,一直在调 用拦截器)
public final void findLove()
{
    CGLIB$CALLBACK_0;

    if(CGLIB$CALLBACK_0 != null) goto _L2; else goto _L1

    _L1:
        JVM INSTR pop;
        CGLIB$BIND_CALLBACKS(this);
        CGLIB$CALLBACK_0;

    _L2:
        JVM INSTR dup ;
        JVM INSTR ifnull 37;
        goto _L3 _L4

    _L3:
        break MISSING_BLOCK_LABEL_21;

    _L4:
        break MISSING_BLOCK_LABEL_37;
        this;
        CGLIB$findLove$0$Method;
        CGLIB$emptyArgs;
        CGLIB$findLove$0$Proxy;
        //调用拦截器
        intercept();
        return;
        super.findLove();
        return;
}

调用过程:
代理对象调用 this.findLove()方法->调用拦截器->methodProxy.invokeSuper->CGLIB$findLove$0->被代理对象 findLove()方法

此时,我们发现拦截器 MethodInterceptor 中就是由 MethodProxy 的 invokeSuper 方法调用代理方法的,MethodProxy 非常关键,我们分析一下它具体做了什么

public class MethodProxy {
    private Signature sig1;
    private Signature sig2;
    private MethodProxy.CreateInfo createInfo;
    private final Object initLock = new Object();
    private volatile MethodProxy.FastClassInfo fastClassInfo;

    public static MethodProxy create(Class c1, Class c2, String desc, String name1, String name2) {
        MethodProxy proxy = new MethodProxy();
        proxy.sig1 = new Signature(name1, desc);
        proxy.sig2 = new Signature(name2, desc);
        proxy.createInfo = new MethodProxy.CreateInfo(c1, c2);
        return proxy;
    }

    ...

    private static class CreateInfo {
        Class c1;
        Class c2;
        NamingPolicy namingPolicy;
        GeneratorStrategy strategy;
        boolean attemptLoad;

        public CreateInfo(Class c1, Class c2) {
            this.c1 = c1;
            this.c2 = c2;
            AbstractClassGenerator fromEnhancer = AbstractClassGenerator.getCurrent();
            if (fromEnhancer != null) {
                this.namingPolicy = fromEnhancer.getNamingPolicy();
                this.strategy = fromEnhancer.getStrategy();
                this.attemptLoad = fromEnhancer.getAttemptLoad();
            }

        }
    }

    ...
}

继续看 invokeSuper()方法

public Object invokeSuper(Object obj, Object[] args) throws Throwable {
    try {
        this.init();
        MethodProxy.FastClassInfo fci = this.fastClassInfo;
        return fci.f2.invoke(fci.i2, obj, args);
    } catch (InvocationTargetException var4) {
        throw var4.getTargetException();
    }
}

...

private static class FastClassInfo {
    FastClass f1;
    FastClass f2;
    int i1;
    int i2;

    private FastClassInfo() {
    }
}

上面代码调用过程就是获取到代理类对应的 FastClass,并执行了代理方法.还记得之前生成三个 class 文件吗?

  • Customer3feeb52a6aad62f1.class 就是代理类的 FastClass
  • Customer2669574a.class 就是被代理类的 FastClass

CGLib 动态代理执行代理方法效率之所以比 JDK 的高是因为 Cglib 采用了 FastClass 机制,它的原理简单来说就是:
为代理类和被代理类各生成一个 Class,这个 Class 会为代理类或被代理类的方法分配一个 index(int 类型).这个 index 当做一个入参,FastClass 就可以直接定位要调用的方法直接进行调用,这样省去了反射调用,所以调用效率比 JDK 动态代理通过反射调用高

6. 总结

6.1 CGlib 动态代理和 JDK 动态代理对比

两种动态代理都是通过生成新的类,去实现增强被代理类代码逻辑的功能

  • JDK 动态代理采用实现被代理对象接口
  • CGlib 动态代理采用继承被代理对象,并覆盖父类方法
  • JDK 动态代理对于用户而言,必须要有一个接口实现,目标类相对来说复杂
  • CGlib 动态代理可以代理任意一个普通的对象,没有任何要求
  • JDK 动态代理生成代理的逻辑简单,执行效率相对较低,每次都要反射动态调用
  • CGlib 生成代理逻辑更加复杂,调用效率更高,生成一个包含了所有的逻辑的 FastClass,不再需要反射调用
  • CGlib 代理有坑,不能代理 final 方法

6.2 代理模式优点

  • 代理模式能将代理对象与真实被调用的目标对象分离
  • 一定程度上降低了系统耦合程度,易于扩展
  • 代理模式起到了保护目标对象的作用
  • 增强目标对象的职责

6.2 代理模式缺点

  • 代理模式会造成系统设计中类的数量增加
  • 在客户端和目标对象之间增加了一个代理对象,会造成请求处理速度变慢
  • 增加了系统的复杂度

7. Spring 与动态代理

7.1 动态代理在 Spring 源码中的应用

先看 ProxyFactoryBean 核心的方法就是 getObject()方法,我们来看一下源码

public Object getObject() throws BeansException {
    initializeAdvisorChain();
    if (isSingleton()) {
        return getSingletonInstance();
    } else {
        if (this.targetName == null) {
            logger.warn("Using non-singleton proxies with singleton targets is often undesirable. "
            + "Enable prototype proxies by setting the 'targetName' property.");
        }
    return newPrototypeInstance();
    }
}

在 getObject()方法中,主要调用 getSingletonInstance()和 newPrototypeInstance()

在 Spring 的配置中,如果不做任何设置,那么 Spring 代理生成的 Bean 都是单例对象.如果修改 scope 则每次创建一个新的原型对象.newPrototypeInstance()里面的逻辑比较复杂,我们后面的课程再做深入研究,这里我们先做简单的了解

Spring 利用动态代理实现 AOP 有两个非常重要的,一个是 JdkDynamicAopProxy 类和 CglibAopProxy 类,来看一下类图

image

7.2 Spring 中代理模式的选择

  • 当 Bean 有实现接口时,Spring 就会用 JDK 的动态代理
  • 当 Bean 没有实现接口时,Spring 会选择 CGlib
  • Spring 可以通过配置强制使用 CGlib,只需在 Spring 的配置文件中加入如下代码

参考资料:
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html

你可能感兴趣的:([01][01][07] 代理模式详解)