Spring AOP 总结三

前两篇文章我们一起梳理了Spring AOP的基本概念及其解析和创建代理的过程,通过梳理我对Spring AOP的认识又向前迈了一大步。不过,对于代理创建过程着墨较少,本篇文章我想继续就这个话题展开,也希望通过这次展开,能让我们对Spring AOP中的CGLIB代理有一些不一样的认识。前一篇文章提到过,Spring创建代理方式是CGLIB(有兴趣的可以浏览一番)。这个创建过程究竟是怎么进行的呢?

首先我们来看一下AbstractAutoProxyCreatorbuildProxy()方法。该方法的源码如下图所示:

Spring AOP 总结三_第1张图片

由图可知,代码会首先ProxyFactory proxyFactory = new ProxyFactory()一句来创建一个ProxyFactory对象。该类的具体结构如下图所示:

Spring AOP 总结三_第2张图片

接着代码会对ProxyFactory对象进行一些初始化,比如advisors、targetSource等。最后会调用ProxyFactory对象上的getProxy(@Nullable ClassLoader classLoader)方法去创建代理对象。该方法的代码如下图所示:

这段代码会首先调用ProxyFactory父类ProxyCreatorSupport中的createAopProxy()方法,这个方法的代码如下图所示:

Spring AOP 总结三_第3张图片

这段代码中蓝色标注的方法就是一个普通的getter方法,其会返回一个AopProxyFactory类型的对象。该对象的初始化是在ProxyCreatorSupport中完成的,具体参见下述代码:

public ProxyCreatorSupport() {
    this.aopProxyFactory = DefaultAopProxyFactory.INSTANCE;
}

这里的DefaultAopProxyFactory.INSTANCE的值是new DefaultAopProxyFactory(),代码位于DefaultAopProxyFactory类中,如下图所示:

Spring AOP 总结三_第4张图片

到这里我们来看一下DefaultAopProxyFactory类的体系结构:

Spring AOP 总结三_第5张图片

再回过头来看蓝色标注的代码块getAopProxyFactory().createAopProxy(this)的后半部分,很自然的可以理解这里调用的是DefaultAopProxyFactory类的createAopProxy(AdvisedSupport config)方法。其代码如下所示:

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
       Class targetClass = config.getTargetClass();
       if (targetClass == null) {
          throw new AopConfigException("TargetSource cannot determine target class: " +
                "Either an interface or a target is required for proxy creation.");
       }
       if (targetClass.isInterface() || Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass)) {
          return new JdkDynamicAopProxy(config);
       }
       return new ObjenesisCglibAopProxy(config);
    }
    else {
       return new JdkDynamicAopProxy(config);
    }
}

根据这段代码不难看出,该方法的主要作用就是创建一个能够创建动态代理对象的建造者对象。这里的建造者不是建造者设计模式,而是一种形象表示,意思是说JdkDynamicAopProxy和ObjenesisCglibAopProxy两个类的对象的主要作用就是创建动态代理对象。前一篇文章中有提到过这个方法最终返回的是ObjenesisCglibAopProxy对象。下面看一下这个类的结构:

Spring AOP 总结三_第6张图片

再次回到ProxyFactory对象的getProxy(@Nullable ClassLoader classLoader)方法中,这里再贴一下这个方法的源码:

public Object getProxy(@Nullable ClassLoader classLoader) {
    return createAopProxy().getProxy(classLoader);
}

我们来看一下这个代码的后半部分,即getProxy(classLoader)。跟踪下去,我们会看到代码来到了CglibAopProxy中,该方法的代码如下所示:

public Object getProxy(@Nullable ClassLoader classLoader) {
    return buildProxy(classLoader, false);
}

这个方法的代码非常简单,调用本类(CglibAopProxy)的buildProxy(@Nullable ClassLoader classLoader, boolean classOnly)方法。下面我们继续看buildProxy()方法源码,如下所示:

private Object buildProxy(@Nullable ClassLoader classLoader, boolean classOnly) {
    if (logger.isTraceEnabled()) {
       logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
    }

    try {
       Class rootClass = this.advised.getTargetClass();
       Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

       Class proxySuperClass = rootClass;
       if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
          proxySuperClass = rootClass.getSuperclass();
          Class[] additionalInterfaces = rootClass.getInterfaces();
          for (Class additionalInterface : additionalInterfaces) {
             this.advised.addInterface(additionalInterface);
          }
       }

       // Validate the class, writing log messages as necessary.
       validateClassIfNecessary(proxySuperClass, classLoader);

       // Configure CGLIB Enhancer...
       Enhancer enhancer = createEnhancer();
       if (classLoader != null) {
          enhancer.setClassLoader(classLoader);
          if (classLoader instanceof SmartClassLoader smartClassLoader &&
                smartClassLoader.isClassReloadable(proxySuperClass)) {
             enhancer.setUseCache(false);
          }
       }
       enhancer.setSuperclass(proxySuperClass);
       enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
       enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
       enhancer.setAttemptLoad(true);
       enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));

       Callback[] callbacks = getCallbacks(rootClass);
       Class[] types = new Class[callbacks.length];
       for (int x = 0; x < types.length; x++) {
          types[x] = callbacks[x].getClass();
       }
       // fixedInterceptorMap only populated at this point, after getCallbacks call above
       ProxyCallbackFilter filter = new ProxyCallbackFilter(
             this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset);
       enhancer.setCallbackFilter(filter);
       enhancer.setCallbackTypes(types);

       // Generate the proxy class and create a proxy instance.
       // ProxyCallbackFilter has method introspection capability with Advisor access.
       try {
          return (classOnly ? createProxyClass(enhancer) : createProxyClassAndInstance(enhancer, callbacks));
       }
       finally {
          // Reduce ProxyCallbackFilter to key-only state for its class cache role
          // in the CGLIB$CALLBACK_FILTER field, not leaking any Advisor state...
          filter.advised.reduceToAdvisorKey();
       }
    }
    catch (CodeGenerationException | IllegalArgumentException ex) {
       throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
             ": Common causes of this problem include using a final class or a non-visible class",
             ex);
    }
    catch (Throwable ex) {
       // TargetSource.getTarget() failed
       throw new AopConfigException("Unexpected AOP exception", ex);
    }
}

我们看这段代码中这一句:Enhancer enhancer = createEnhancer(),这里创建了一个Enhancer对象,这个对象就是创建Cglib动态代理的关键。继续看后面的代码不难发现,主要操作就是初始化Enhancer对象的各个属性。到Callback[] callbacks = getCallbacks(rootClass)这行代码时我们要停一下。进入getCallbacks(Class rootClass)方法,个人理解这个方法的主要作用就是创建拦截器组,最终会返回一个由以下几个类组成的拦截器数组:

  1. DynamicAdvisedInterceptor(对应的变量名为:aopInterceptor),根据debug,个人觉得这个拦截器的主要作用是执行切面方法
  2. StaticUnadvisedExposedInterceptor(对应的变量名为:targetInterceptor)
  3. SerializableNoOp
  4. StaticDispatcher(对应的变量名为:targetDispatcher)
  5. AdvisedDispatcher(对应的变量名为:advisedDispatcher)
  6. EqualsInterceptor
  7. HashCodeInterceptor

继续代码,后面的Class[] types = new Class[callbacks.length]一句,主要用于存放所有拦截器的实际类型,最后可以看到这样一句代码:

return (classOnly ? createProxyClass(enhancer) : createProxyClassAndInstance(enhancer, callbacks));

最终走的是createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks)方法,走的是子类ObjenesisCglibAopProxy中的方法。该方法的主要作用就是生成字节码,并依据此字节码创建一个代理对象,该方法的代码如下图所示:

Spring AOP 总结三_第7张图片

至此系统就为我们创建了一个代理对象。下面我们看一下代理对象创建过程中涉及的几个类的结构:

  • Enhancer

Spring AOP 总结三_第8张图片

  • DynamicAdvisedInterceptor| StaticUnadvisedExposedInterceptor| SerializableNoOp| StaticDispatcher| AdvisedDispatcher| EqualsInterceptor| HashCodeInterceptor

Spring AOP 总结三_第9张图片

你可能感兴趣的:(Spring,spring,java)