经典三层框架初识(二)---Spring 3.2动态代理

上面的遗留问题需要我们使用这次讲的动态代理来解决.由于在网上看到一个关于动态代理富含源码解释的文章,觉得很棒.这里就通过转载的方式和大家分享一下.

动态代理JDK代理:

  • 动态代理有以下特点:

    • 代理对象,不需要实现接口
    • 代理对象的生成,是利用JDK的API,动态的在内存中创建代理对象(需要我们指定创建代理对象/目标对象实现的接口的类型)

    • 动态代理也叫做:JDK代理,接口代理
  • JDK中生成代理对象的API

    • 代理类所在包:java.lang.reflect.Proxy.JDK实现代理只需要使用newProxyInstance方法,但是该方法需要接收三个参数,完整的写法是:static Object newProxyInstance(ClassLoader loader, Class<?>[ ] interfaces,InvocationHandler h )
    • 方法是在Proxy类中是静态方法,且接收的三个参数依次为:
      • ClassLoader loader  //指定当前目标对象使用类加载器
      • Class<?>[ ] interfaces  //目标对象实现的接口的类型,使用泛型方式确认类型
      • InvocationHandler h  //事件处理器
  • 下面进行代码演示:

    • 接口类IUserDao
    • /**
       * 接口
       */
      public interface IUserDao {
      
          void save();
      
      }

      目标对象UserDao

    • /**
       * 接口实现
       * 目标对象
       */
      public class UserDao implements IUserDao {
      
          public void save() {
      
              System.out.println("----保存数据成功!----");
          }
      
      }

      代理工厂类:ProxyFactory

    • /**
       * 创建动态代理对象
       * 动态代理不需要实现接口,但是需要指定接口类型
       */
      public class ProxyFactory{
      
          //维护一个目标对象
          private Object target;
          public ProxyFactory(Object target){
              this.target=target;
          }
      
         //给目标对象生成代理对象
          public Object getProxyInstance(){
              return Proxy.newProxyInstance(
                      target.getClass().getClassLoader(),
                      target.getClass().getInterfaces(),
                      new InvocationHandler() {
                          @Override
                          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                              System.out.println("开始事务111");
                              //执行目标对象方法
                              Object returnValue = method.invoke(target, args);
                              System.out.println("提交事务111");
                              return returnValue;
                          }
                      }
              );
          }
      
      }

      测试类:App:

    • /**
       * 测试类
       */
      public class App {
          public static void main(String[] args) {
              // 目标对象
              IUserDao target = new UserDao();
              // 【原始的类型 class com.zhong.UserDao】
              System.out.println(target.getClass());
      
              // 给目标对象,创建代理对象
              IUserDao proxy = (IUserDao) new ProxyFactory(target).getProxyInstance();
              // class $Proxy0   内存中动态生成的代理对象
              System.out.println(proxy.getClass());
      
              // 执行方法   【代理对象】
              proxy.save();
          }
      }

      在这里我们会想:代理对象是谁,是如何生成这个代理对象的呢?接下来我们主要看这个方法  getProxyInstance() 

    • //给目标对象生成代理对象
          public Object getProxyInstance(){
              return Proxy.newProxyInstance(
                      target.getClass().getClassLoader(),
                      target.getClass().getInterfaces(),
                      new InvocationHandler() {
                          @Override
                          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                              System.out.println("开始事务111");
                              //执行目标对象方法
                              Object returnValue = method.invoke(target, args);
                              System.out.println("提交事务111");
                              return returnValue;
                          }
                      }
              );

      我们看到其返回了一个Proxy类的对象,即JDK的动态代理,是通过一个叫Proxy的类的静态方法newProxyInstance来实现的,其那么我们就去它的源码里看一下它到底都做了些什么?

    • public static Object newProxyInstance(ClassLoader loader,
                                                Class>[] interfaces,
                                                InvocationHandler h)
              throws IllegalArgumentException
          {
              //检查h 不为空,否则抛异常
              Objects.requireNonNull(h);
       
              final Class>[] intfs = interfaces.clone();
              final SecurityManager sm = System.getSecurityManager();
              if (sm != null) {
                  checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
              }
       
              /*
               * 获得与指定类装载器和一组接口相关的代理类类型对象
               */
              Class> cl = getProxyClass0(loader, intfs);
       
              /*
               * 通过反射获取构造函数对象并生成代理类实例
               */
              try {
                  if (sm != null) {
                      checkNewProxyPermission(Reflection.getCallerClass(), cl);
                  }
                  //获取代理对象的构造方法(也就是$Proxy0(InvocationHandler h)) 
                  final Constructor> cons = cl.getConstructor(constructorParams);
                  final InvocationHandler ih = h;
                  if (!Modifier.isPublic(cl.getModifiers())) {
                      AccessController.doPrivileged(new PrivilegedAction() {
                          public Void run() {
                              cons.setAccessible(true);
                              return null;
                          }
                      });
                  }
                  //生成代理类的实例并把InvocationHandlerImpl的实例传给它的构造方法
                  return cons.newInstance(new Object[]{h});
              } catch (IllegalAccessException|InstantiationException e) {
                  throw new InternalError(e.toString(), e);
              } catch (InvocationTargetException e) {
                  Throwable t = e.getCause();
                  if (t instanceof RuntimeException) {
                      throw (RuntimeException) t;
                  } else {
                      throw new InternalError(t.toString(), t);
                  }
              } catch (NoSuchMethodException e) {
                  throw new InternalError(e.toString(), e);
              }
          }

      上面的代码表明,首先通过getProxyClass0获得这个代理类,然后通过c1.getConstructor()拿到构造函数,最后一步,通过cons.newInstance返回这个新的代理类的一个实例,注意:调用newInstance的时候,传入的参数为h,即我们自己定义好的InvocationHandler类 。我们再进去getProxyClass0方法看一下:

    • 扫描二维码关注公众号,回复: 3937235 查看本文章
      /**
           * Generate a proxy class.  Must call the checkProxyAccess method
           * to perform permission checks before calling this.
           */
          private static Class> getProxyClass0(ClassLoader loader,
                                                 Class>... interfaces) {
              if (interfaces.length > 65535) {
                  throw new IllegalArgumentException("interface limit exceeded");
              }
       
              // If the proxy class defined by the given loader implementing
              // the given interfaces exists, this will simply return the cached copy;
              // otherwise, it will create the proxy class via the ProxyClassFactory
              return proxyClassCache.get(loader, interfaces);
          }

      这里用到了缓存,先从缓存里查一下,如果存在,直接返回,不存在就新创建。

      真相还是没有来到,继续,看一下proxyClassCache

    • /**
           * a cache of proxy classes
           */
          private static final WeakCache[], Class>>
              proxyClassCache = new WeakCache(new KeyFactory(), new ProxyClassFactory());

      再看下proxyClassCache.get方法,

    • public synchronized V get() { // serialize access
                  // re-check
                  Supplier supplier = valuesMap.get(subKey);
                  if (supplier != this) {
                      // something changed while we were waiting:
                      // might be that we were replaced by a CacheValue
                      // or were removed because of failure ->
                      // return null to signal WeakCache.get() to retry
                      // the loop
                      return null;
                  }
                  // else still us (supplier == this)
       
                  // create new value
                  V value = null;
                  try {
                      value = Objects.requireNonNull(valueFactory.apply(key, parameter));
                  } finally {
                      if (value == null) { // remove us on failure
                          valuesMap.remove(subKey, this);
                      }
                  }
                  // the only path to reach here is with non-null value
                  assert value != null;
       
                  // wrap value with CacheValue (WeakReference)
                  CacheValue cacheValue = new CacheValue(value);
       
                  // try replacing us with CacheValue (this should always succeed)
                  if (valuesMap.replace(subKey, this, cacheValue)) {
                      // put also in reverseMap
                      reverseMap.put(cacheValue, Boolean.TRUE);
                  } else {
                      throw new AssertionError("Should not reach here");
                  }
       
                  // successfully replaced us with new CacheValue -> return the value
                  // wrapped by it
                  return value;
              }
          }

      其中,value = Objects.requireNonNull(valueFactory.apply(key, parameter));

      提到了apply(),是Proxy类的内部类ProxyClassFactory实现其接口的一个方法,具体实现如下:

    • /**
           * A factory function that generates, defines and returns the proxy class given
           * the ClassLoader and array of interfaces.
           */
          private static final class ProxyClassFactory
              implements BiFunction[], Class>>
          {
              // prefix for all proxy class names
              private static final String proxyClassNamePrefix = "$Proxy";
       
              // next number to use for generation of unique proxy class names
              private static final AtomicLong nextUniqueNumber = new AtomicLong();
       
              @Override
              public Class> apply(ClassLoader loader, Class>[] interfaces) {
       
                  Map, Boolean> interfaceSet = new IdentityHashMap(interfaces.length);
                  for (Class> intf : interfaces) {
                      /*
                       * Verify that the class loader resolves the name of this
                       * interface to the same Class object.
                       */
                      Class> interfaceClass = null;
                      try {
                          interfaceClass = Class.forName(intf.getName(), false, loader);
                      } catch (ClassNotFoundException e) {
                      }
                      if (interfaceClass != intf) {
                          throw new IllegalArgumentException(
                              intf + " is not visible from class loader");
                      }
                      /*
                       * Verify that the Class object actually represents an
                       * interface.
                       */
                      if (!interfaceClass.isInterface()) {
                          throw new IllegalArgumentException(
                              interfaceClass.getName() + " is not an interface");
                      }
                      /*
                       * Verify that this interface is not a duplicate.
                       */
                      if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                          throw new IllegalArgumentException(
                              "repeated interface: " + interfaceClass.getName());
                      }
                  }
       
                  String proxyPkg = null;     // package to define proxy class in
                  int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
       
                  /*
                   * Record the package of a non-public proxy interface so that the
                   * proxy class will be defined in the same package.  Verify that
                   * all non-public proxy interfaces are in the same package.
                   */
                  for (Class> intf : interfaces) {
                      int flags = intf.getModifiers();
                      if (!Modifier.isPublic(flags)) {
                          accessFlags = Modifier.FINAL;
                          String name = intf.getName();
                          int n = name.lastIndexOf('.');
                          String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                          if (proxyPkg == null) {
                              proxyPkg = pkg;
                          } else if (!pkg.equals(proxyPkg)) {
                              throw new IllegalArgumentException(
                                  "non-public interfaces from different packages");
                          }
                      }
                  }
       
                  if (proxyPkg == null) {
                      // if no non-public proxy interfaces, use com.sun.proxy package
                      proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
                  }
       
                  /*
                   * Choose a name for the proxy class to generate.
                   */
                  long num = nextUniqueNumber.getAndIncrement();
                  String proxyName = proxyPkg + proxyClassNamePrefix + num;
       
                  /*
                   * Generate the specified proxy class.
                   */
                  byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                      proxyName, interfaces, accessFlags);
                  try {
                      return defineClass0(loader, proxyName,
                                          proxyClassFile, 0, proxyClassFile.length);
                  } catch (ClassFormatError e) {
                      /*
                       * A ClassFormatError here means that (barring bugs in the
                       * proxy class generation code) there was some other
                       * invalid aspect of the arguments supplied to the proxy
                       * class creation (such as virtual machine limitations
                       * exceeded).
                       */
                      throw new IllegalArgumentException(e.toString());
                  }
              }
          }

      这里我们看到了熟悉的方法Class.forName();要加载指定的接口,即是生成类,那就有对应的class字节码

    • /生成字节码
      byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);

      接下来我们也使用测试一下,使用这个方法生成的字节码是个什么样子:

    • package com.adam.java.basic;
      
      import java.io.FileOutputStream;
      import java.io.IOException;
      import sun.misc.ProxyGenerator;
      
      public class DynamicProxyTest {
      
          public static void main(String[] args) {
      
               IUserDao  userdao = new UserDao();
      
               ProxyFactory  handler = new  ProxyFactory  (
                      userdao);
      
              IUserDao   proxy = (IUserDao ) handler.getProxyInstance();
      
              proxy.save();
              
              String path = "C:/$Proxy0.class";
              byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0",
                      UserDao.class.getInterfaces());
              FileOutputStream out = null;
      
              try {
                  out = new FileOutputStream(path);
                  out.write(classFile);
                  out.flush();
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  try {
                      out.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
      }

      不是原始的IUserDao里的save()方法了,而是新生成的代理类的save()方法,我们将生成的$Proxy0.class文件用jd-gui打开

    • public final void save()
          throws 
        {
          try
          {
            this.h.invoke(this, m3, null);
            return;
          }
          catch (Error|RuntimeException localError)
          {
            throw localError;
          }
          catch (Throwable localThrowable)
          {
            throw new UndeclaredThrowableException(localThrowable);
          }
        }

      核心就在于this.h.invoke(this. m3, null);此处的h是啥呢?我们看看这个类的类名:

      public final class $Proxy0 extends Proxy implements IUserDao

      不难发现,新生成的这个类,继承了Proxy类实现了IUserDao这个接口,而这个UserService就是我们指定的接口,所以,这里我们基本可以断定,JDK的动态代理,生成的新代理类就是继承了Proxy基类,实现了传入的接口的类。那这个h到底是啥呢?我们再看看这个新代理类,看看构造函数:

    • public $Proxy0(InvocationHandler paramInvocationHandler)  
          throws   
        {  
          super(paramInvocationHandler);  
      
        }

      这里传入了InvocationHandler类型的参数,而之前有一句代码:

      return cons.newInstance(new Object[]{h}); 

      这是newInstance方法的最后一句,传入的h,就是这里用到的h,也就是我们最初自己定义的MyInvocationHandler类的实例。所以,我们发现,其实最后调用的save()方法,其实调用的是ProxyFactory的invoke()方法.继续看:

    • static
        {
          try
          {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
            m3 = Class.forName("com.zhong.IUserDao").getMethod("save", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
            return;
          }

      m3就是原接口的save()方法.

    • 通过跟踪提示代码可以看出:当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用。

  • 总结:

    • 动态代理实现过程:
    • 1. 通过getProxyClass0()生成代理类。JDK生成的最终真正的代理类,它继承自Proxy并实现了我们定义的接口.
    • 2. 通过Proxy.newProxyInstance()生成代理类的实例对象,创建对象时传入InvocationHandler类型的实例。
    • 3. 调用新实例的方法,即此例中的save(),即原InvocationHandler类中的invoke()方法。
  • 代理对象不需要实现接口,但是目标对象一定要实现接口,否则不能用动态代理

猜你喜欢

转载自blog.csdn.net/XiaodunLP/article/details/83477542
今日推荐