栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring AOP源码3:实现代理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring AOP源码3:实现代理

参考文章:

《Spring AOP源码学习:创建 AOP 代理》

《Spring AOP源码学习:一次请求调用全流程》

前文:

《Spring AOP源码:开启注解读取》

《Spring AOP源码2:查找增强器》

写在开头:本文为个人学习笔记,内容比较随意,夹杂个人理解,如有错误,欢迎指正。

        在前文中,我们找到了所有适用于当前bean的增强器,本文我们就为他们创建适用于他们的代理类。

一、createProxy         1、createProxy

        在生成代理类之前,主要做了两件事,判断使用 Jdk 代理还是 Cglib 代理以及设置相关的属性。

protected Object createProxy(
        Class beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
     // 如果当前beanFactory实现了ConfigurableListableBeanFactory接口,则将需要被代理的对象暴露出来
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }
 
    // 创建代理工厂
    ProxyFactory proxyFactory = new ProxyFactory();
    // 从当前对象复制属性值
    proxyFactory.copyFrom(this);
 
    // 检查proxyTargetClass属性,判断对于给定的bean使用类代理还是接口代理,
    // proxyTargetClass值默认为false,可以通过proxy-target-class属性设置为true
    if (!proxyFactory.isProxyTargetClass()) {
        // 检查preserveTargetClass属性,判断beanClass是应该基于类代理还是基于接口代理
        if (shouldProxyTargetClass(beanClass, beanName)) {
            // 如果是基于类代理,则将proxyTargetClass赋值为true
            proxyFactory.setProxyTargetClass(true);
        } else {
            // 判断目标类是否实现了相关接口
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }
    // 将拦截器封装为Advisor(advice持有者)
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    // 将advisors添加到proxyFactory
    proxyFactory.addAdvisors(advisors);
    // 设置要代理的类,将targetSource赋值给proxyFactory的targetSource属性,之后可以通过该属性拿到被代理的bean的实例
    proxyFactory.setTargetSource(targetSource);
    // 自定义ProxyFactory,空方法,留给子类实现
    customizeProxyFactory(proxyFactory);
 
    // 用来控制proxyFactory被配置之后,是否还允许修改通知。默认值为false(即在代理被配置之后,不允许修改代理类的配置)
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
 
    // 使用proxyFactory生成代理
    return proxyFactory.getProxy(getProxyClassLoader());
}
        2、createProxy

        可以理解为一个工厂方法,返回值是一个 AopProxy 类型的对象,其内部根据具体的条件生成相应的子类对象,即 JdkDynamicAopProxy 和 ObjenesisCglibAopProxy。后面则通过调用 AopProxy.getProxy() 方法获取代理过的对象。

public Object getProxy(ClassLoader classLoader) {
    // 首先创建AopProxy对象,其主要有两个实现:JdkDynamicAopProxy和ObjenesisCglibAopProxy,
    // 分别用于Jdk和Cglib代理类的生成,其getProxy()方法则用于获取具体的代理对象
    return createAopProxy().getProxy(classLoader);
}

        3、createAopProxy

        真正创建了AopProxy的实现类,根据不同的条件判断是创建JdkDynamicAopProxy 还是 ObjenesisCglibAopProxy,这两个分别对应了JDK与CGLIB的代理类生成方式。

protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        // 1.激活此代理配置
        activate();
    }
    // 2.创建AopProxy
    return getAopProxyFactory().createAopProxy(this);
}
 
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    // 1.判断使用JDK动态代理还是Cglib代理
    // optimize:用于控制通过cglib创建的代理是否使用激进的优化策略。除非完全了解AOP如何处理代理优化,
    // 否则不推荐使用这个配置,目前这个属性仅用于cglib代理,对jdk动态代理无效
    // proxyTargetClass:默认为false,设置为true时,强制使用cglib代理,设置方式:
    // hasNoUserSuppliedProxyInterfaces:config是否存在代理接口或者只有SpringProxy一个接口
    if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
        // 拿到要被代理的对象的类型
        Class targetClass = config.getTargetClass();
        if (targetClass == null) {
            // TargetSource无法确定目标类:代理创建需要接口或目标。
            throw new AopConfigException("TargetSource cannot determine target class: " +
                    "Either an interface or a target is required for proxy creation.");
        }
        // 如果被代理的类是一个接口,或者被代理的类是使用Jdk代理生成的类,此时还是使用Jdk代理
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            // JDK动态代理,这边的入参config(AdvisedSupport)实际上是ProxyFactory对象
            return new JdkDynamicAopProxy(config);
        }
        // Cglib代理
        return new ObjenesisCglibAopProxy(config);
    } else {
        // JDK动态代理
        return new JdkDynamicAopProxy(config);
    }
}

 

二、JdkDynamicAopProxy         1、JdkDynamicAopProxy

        JdkDynamicAopProxy的构造方法,内容很简单,就是将之前创建的ProxyFactory对象赋值给成员变量advised。

// JdkDynamicAopProxy.java
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
    Assert.notNull(config, "AdvisedSupport must not be null");
    if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
        throw new AopConfigException("No advisors and no TargetSource specified");
    }
    // config赋值给advised
    this.advised = config;
}
 
        2、getProxy

        (1)获取生成代理对象所需要实现的所有接口

        (2)然后判断接口中是否包含有 equals () 和 hashCode () 方法,因为这将用于判断生成的代理类是使用用于定义的 equals () 和 hashCode () 方法还是使用自动生成的方法

        (3)通过动态代理生成代理对象

        这里需要注意的是 JdkDynamicAopProxy 不仅实现了 AopProxy 接口还实现了 InvocationHandler 接口,因而这里生成代理对象的时候传入的 InvocationHandler 对象是 this。

@Override
public Object getProxy(ClassLoader classLoader) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
    }
    // 拿到要被代理对象的所有接口
    Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    // 找到接口中是否包含有equals()和hashCode()方法,并进行标识
    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
    // 通过classLoader、接口、InvocationHandler实现类生成代理对象
    return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

        到这里,使用JDK动态代理创建的代理类已经完成了,当JDK动态代理的类被调用时,会走到 JdkDynamicAopProxy#invoke 方法。

        3、invoke 

        判断目标方法是否为 Spring 织入的 Advised 中的方法,如果是,则调用当前 advised 对象中相应的方法。然后就会获取当前方法需要织入的代理逻辑的调用链。接着就会将目标对象和调用链逻辑封装为 ReflectiveMethodInvocation,并进行调用。

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    MethodInvocation invocation;
    Object oldProxy = null;
    boolean setProxyContext = false;
 
    // advised就是proxyFactory,而targetSource持有被代理对象的引用
    TargetSource targetSource = this.advised.targetSource;
    Class targetClass = null;
    Object target = null;
 
    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // 如果当前方法是equals()方法,并且接口中并未定义该方法,就使用自动生成的equals()方法
            return equals(args[0]);
        }
        else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // 如果当前方法是hashCode()方法,并且接口中并未定义该方法,就使用自动生成的hashCode()方法
            return hashCode();
        } else if (method.getDeclaringClass() == DecoratingProxy.class) {
            // 如果当前方法是Spring织入的DecoratingProxy接口中的方法,则返回目标对象的Class类型
            return AopProxyUtils.ultimateTargetClass(this.advised);
        } else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                method.getDeclaringClass().isAssignableFrom(Advised.class)) {
            // 如果当前方法是Spring织入的Advised接口中的方法,则使用反射调用当前advised对象中的相关方法
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }
 
        Object retVal;
 
        // 如果设置了需要暴露代理对象,则将当前对象设置到AopContext中
        if (this.advised.exposeProxy) {
            // Make invocation available if necessary.
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }
        
        // 拿到我们被代理的对象实例
        target = targetSource.getTarget();
        if (target != null) {
            targetClass = target.getClass();
        }
 
        // 获取当前方法需要织入的切面逻辑的调用链
        List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
        
        // 检查我们是否有任何拦截器(advice)。 如果没有,直接反射调用目标,并避免创建MethodInvocation。
        if (chain.isEmpty()) {
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            // 不存在拦截器链,则直接进行反射调用
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
        } else {
            // We need to create a method invocation...
            // 如果存在拦截器,则创建一个ReflectiveMethodInvocation:代理对象、被代理对象、方法、参数、
            // 被代理对象的Class、拦截器链作为参数创建ReflectiveMethodInvocation
            invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
            // Proceed to the joinpoint through the interceptor chain.
            // 触发ReflectiveMethodInvocation的执行方法
            retVal = invocation.proceed();
        }
 

        // 必要时转换返回值
        Class returnType = method.getReturnType();
        if (retVal != null && retVal == target &&
                returnType != Object.class && returnType.isInstance(proxy) &&
                !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
            // 判断返回值如果为目标对象,并且当前方法的返回值类型是当前代理对象的类型,那么就将
            // 当前代理对象返回。这里的逻辑的实际意思简单的说就是,如果返回值是目标对象,那么
            // 就将当前代理对象返回
            retVal = proxy;
        } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
            // 如果返回值满足其为空,不是Void类型,并且是基本数据类型,那么就抛出异常,
            // 因为基本数据类型的返回值必然不为空
            throw new AopInvocationException(
                    "Null return value from advice does not match primitive return type for: " + method);
        }
        return retVal;
    } finally {
        if (target != null && !targetSource.isStatic()) {
            // 如果TargetSource不是静态的,则调用其releaseTarget()方法将生成的目标对象释放
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // 处理AopContext中保存的当前代理对象
            AopContext.setCurrentProxy(oldProxy);
        }
    }
} 

三、ObjenesisCglibAopProxy         1、ObjenesisCglibAopProxy

        CGLIB实际会会创建CglibAopProxy类作为代理类的创建者。

// ObjenesisCglibAopProxy.java
public ObjenesisCglibAopProxy(AdvisedSupport config) {
	super(config);
}
 
// CglibAopProxy.java
public CglibAopProxy(AdvisedSupport config) throws AopConfigException {
    Assert.notNull(config, "AdvisedSupport must not be null");
    if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
        throw new AopConfigException("No advisors and no TargetSource specified");
    }
    this.advised = config;
    this.advisedDispatcher = new AdvisedDispatcher(this.advised);
}
        2、getProxy

        由于CGLIB的规则是生成一个被代理类的子类,所以这里首先拿到被代理类,并判断这个被代理类是否已经被代理过。然后检查是否有final关键字,我们知道final修饰的成员变量、方法是不会被子类继承的。然后创建当前被代理类的Enhancer并调用getCallbacks方法获取拦截器,最后调用createProxyClassAndInstance。

@Override
public Object getProxy(ClassLoader classLoader) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
    }
 
    try {
        // 1.拿到要代理目标类
        Class rootClass = this.advised.getTargetClass();
        Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
 
        // proxySuperClass默认为rootClass
        Class proxySuperClass = rootClass;
        if (ClassUtils.isCglibProxyClass(rootClass)) {
            // 如果rootClass是被Cglib代理过的,获取rootClass的父类作为proxySuperClass
            proxySuperClass = rootClass.getSuperclass();
            Class[] additionalInterfaces = rootClass.getInterfaces();
            for (Class additionalInterface : additionalInterfaces) {
                // 将父类的接口也添加到advised的interfaces属性
                this.advised.addInterface(additionalInterface);
            }
        }
 
        // Validate the class, writing log messages as necessary.
        // 2.校验proxySuperClass,主要是校验方法是否用final修饰、跨ClassLoader的包可见方法,如果有将警告写入日志
        validateClassIfNecessary(proxySuperClass, classLoader);
 
        // Configure CGLIB Enhancer...
        // 3.创建和配置Cglib Enhancer
        Enhancer enhancer = createEnhancer();
        if (classLoader != null) {
            enhancer.setClassLoader(classLoader);
            if (classLoader instanceof SmartClassLoader &&
                    ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                enhancer.setUseCache(false);
            }
        }
        // superclass为被代理的目标类proxySuperClass,通过名字可以看出,生成的代理类实际上是继承了被代理类
        enhancer.setSuperclass(proxySuperClass);
        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
 
        // 4.获取所有要回调的拦截器
        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
        // 在上面调用getCallbacks之后,此时仅填充fixedInterceptorMap
        enhancer.setCallbackFilter(new ProxyCallbackFilter(
                this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
        enhancer.setCallbackTypes(types);
 
        // Generate the proxy class and create a proxy instance.
        // 5.生成代理类并创建代理实例,返回代理实例
        return createProxyClassAndInstance(enhancer, callbacks);
    } catch (CodeGenerationException ex) {
        throw new AopConfigException("Could not generate CGLIB subclass of class [" +
                this.advised.getTargetClass() + "]: " +
                "Common causes of this problem include using a final class or a non-visible class",
                ex);
    } catch (IllegalArgumentException ex) {
        throw new AopConfigException("Could not generate CGLIB subclass of class [" +
                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);
    }
}

        3、getCallbacks
private Callback[] getCallbacks(Class rootClass) throws Exception {

    // 用于优化选择的参数
    boolean exposeProxy = this.advised.isExposeProxy();
    boolean isFrozen = this.advised.isFrozen();
    boolean isStatic = this.advised.getTargetSource().isStatic();
 
    // 创建自定义的被代理类拦截器,这里的this.advised就是之前创建
    // CglibAopProxy时传进来的ProxyFactory(ProxyCreatorSupport子类)
    Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);
 

    Callback targetInterceptor;
    // 判断如果要暴露代理对象
    if (exposeProxy) {
        // 判断被代理的对象是否是静态的,如果是静态的,则将目标对象缓存起来,每次都使用该对象即可,
        // 如果目标对象是动态的,则在DynamicUnadvisedExposedInterceptor中每次都生成一个新的目标对象
        targetInterceptor = isStatic ?
                new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
                new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource());
    } else {
        // 是否使用AopContext暴露生成的代理对象
        targetInterceptor = isStatic ?
                new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
                new DynamicUnadvisedInterceptor(this.advised.getTargetSource());
    }
 

    Callback targetDispatcher = isStatic ?
            new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp();
 
    // 将aop拦截器添加到mainCallbacks中
    Callback[] mainCallbacks = new Callback[]{
            aopInterceptor,  // 用户自己定义的拦截器
            targetInterceptor,  // 根据条件是否暴露代理对象的拦截器
            new SerializableNoOp(),  // 不做任何操作的拦截器
            targetDispatcher, this.advisedDispatcher, // 用于存储Advised对象的分发器
            new EqualsInterceptor(this.advised),    // 针对equals方法的拦截器
            new HashCodeInterceptor(this.advised)   // 针对hashcode方法的拦截器
    };
 
    Callback[] callbacks;
 
    // 如果目标对象是静态的,并且切面逻辑的调用链是固定的,
    // 则对目标对象和整个调用链进行缓存
    if (isStatic && isFrozen) {
        Method[] methods = rootClass.getMethods();
        Callback[] fixedCallbacks = new Callback[methods.length];
        this.fixedInterceptorMap = new HashMap(methods.length);
 

        for (int x = 0; x < methods.length; x++) {
            List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass);
            fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
                    chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
            this.fixedInterceptorMap.put(methods[x].toString(), x);
        }
 

        callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
        System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
        System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
        this.fixedInterceptorOffset = mainCallbacks.length;
    } else {
        callbacks = mainCallbacks;
    }
    return callbacks;
} 
        4、DynamicAdvisedInterceptor#intercept 

        这里intercept的作用和JdkDynamicAopProxy#invoke中的作用一样.

        (1)为目标对象生成切面逻辑调用链;
        (2)通过切面逻辑对目标对象进行环绕,并且进行调用。

		@Override
		public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
			Object oldProxy = null;
			boolean setProxyContext = false;
			Class targetClass = null;
			Object target = null;
			try {
                // 判断如果需要暴露代理对象,则将当前代理对象设置到ThreadLocal中
				if (this.advised.exposeProxy) {
					oldProxy = AopContext.setCurrentProxy(proxy);
					setProxyContext = true;
				}
				target = getTarget();
				if (target != null) {
					targetClass = target.getClass();
				}
                // 获取目标对象切面逻辑的环绕链
				List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
				Object retVal;
				if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
                    // 对参数进行处理,以使其与目标方法的参数类型一致,尤其对于数组类型,
                    // 会单独处理其数据类型与实际类型一致
					Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                    // 因为没有切面逻辑需要织入,这里直接调用目标方法
					retVal = methodProxy.invoke(target, argsToUse);
				}
				else {
                    // 通过生成的调用链,对目标方法进行环绕调用
					retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
				}
                // 对返回值进行处理,如果返回值就是当前目标对象,那么将代理生成的代理对象返回;
                // 如果返回值为空,并且返回值类型是非void的基本数据类型,则抛出异常;
                // 如果上述两个条件都不符合,则直接将生成的返回值返回
				retVal = processReturnType(proxy, target, method, retVal);
				return retVal;
			}
			finally {
                // 如果目标对象不为空,则释放目标对象
				if (target != null) {
					releaseTarget(target);
				}
                // 将代理对象设置为前面(外层逻辑)调用设置的对象,以防止暴露出来的代理对象不一致
				if (setProxyContext) {
					AopContext.setCurrentProxy(oldProxy);
				}
			}
		} 

        以上,基于@AspectJ注解实现的AOP原理基本介绍完毕,整体流程基本整理如下:

(1)使用开启AOP注解解析,并注册对应的内部管理的自动代理创建者的 bean:AnnotationAwareAspectJAutoProxyCreator。

(2)容器创建bean到初始化阶段时,调用postProcessAfterInitialization 方法,此时调用此时就会调用我们的 AnnotationAwareAspectJAutoProxyCreator类重写的该方法,然后先查询出所有的增强器(即@Before、@After、@Around 等注解),并根据 @Pointcut 的 execution 表达式筛选出适用于当前遍历的 bean 的增强器, 将适用于当前遍历的 bean 的增强器作为参数之一创建对应的 AOP 代理。

(3)当调用到被 AOP 代理的方法时,会走到对应的代理方法:JdkDynamicAopProxy#invoke 或  DynamicAdvisedInterceptor#intercept,该方法会创建 ReflectiveMethodInvocation,通过责任链的方式来执行所有的增强器和被代理的方法。

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号