Spring AOP –JDK动态代理形式

大家了然Spring是经过JDK可能CGLib落成动态代理的,前些天大家探究一下JDK达成动态代理的规律。

一、简述

Spring在解析Bean的定义之后会将Bean的定义生成三个BeanDefinition对象并且由BeanDefinitionHolder对象拥有。在这一个进度中,尽管Bean须要被打招呼切入,BeanDefinition会被再度转换到三个proxyDefinition(其实也是贰个BeanDefinition对象,只但是描述的是2个ProxyFactoryBean)。ProxyFactoryBean是一个兑现了FactoryBean的接口,用来变化被被切入的靶子。Spring
AOP的落到实处基本上是由此ProxyFactoryBean已毕的。大家明天商讨的首要也是其一类。
  在探讨ProxyFactoryBean以前,大家先看一下2个BeanDefinition转换到proxyDefintion的经过。

public final BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definitionHolder, ParserContext parserContext) {
        BeanDefinitionRegistry registry = parserContext.getRegistry();

        // get the root bean name - will be the name of the generated proxy factory bean
        String existingBeanName = definitionHolder.getBeanName();
        BeanDefinition targetDefinition = definitionHolder.getBeanDefinition();
        BeanDefinitionHolder targetHolder = new BeanDefinitionHolder(targetDefinition, existingBeanName + ".TARGET");

        // delegate to subclass for interceptor definition
        BeanDefinition interceptorDefinition = createInterceptorDefinition(node);

        // generate name and register the interceptor
        String interceptorName = existingBeanName + "." + getInterceptorNameSuffix(interceptorDefinition);
        BeanDefinitionReaderUtils.registerBeanDefinition(
                new BeanDefinitionHolder(interceptorDefinition, interceptorName), registry);

        BeanDefinitionHolder result = definitionHolder;

        if (!isProxyFactoryBeanDefinition(targetDefinition)) {
            // create the proxy definition 这里创建proxyDefinition对象,并且从原来的BeanDefinition对象中复制属性
            RootBeanDefinition proxyDefinition = new RootBeanDefinition();
            // create proxy factory bean definition
            proxyDefinition.setBeanClass(ProxyFactoryBean.class);
            proxyDefinition.setScope(targetDefinition.getScope());
            proxyDefinition.setLazyInit(targetDefinition.isLazyInit());
            // set the target
            proxyDefinition.setDecoratedDefinition(targetHolder);
            proxyDefinition.getPropertyValues().add("target", targetHolder);
            // create the interceptor names list
            proxyDefinition.getPropertyValues().add("interceptorNames", new ManagedList<String>());
            // copy autowire settings from original bean definition.
            proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
            proxyDefinition.setPrimary(targetDefinition.isPrimary());
            if (targetDefinition instanceof AbstractBeanDefinition) {
                proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
            }
            // wrap it in a BeanDefinitionHolder with bean name
            result = new BeanDefinitionHolder(proxyDefinition, existingBeanName);
        }

        addInterceptorNameToList(interceptorName, result.getBeanDefinition());
        return result;
    }

二、ProxyFactoryBean的原理
我们先来看一下ProxyFactoryBean的延续关系:

ProxyFactoryBean类图

ProxyFactoryBean完毕了FactoryBean、BeanClassLoaderAware、BeanFactoryAware接口,那里就不多说了。ProxyCreatorSupport那一个类则是创立代理对象的关键所在。  大家先来探视暴发代理对象的主意:

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

initializeAdvisorChain()
方法是将通报链实例化。然后判断目的是或不是要生成单例而挑选调用不一致的不二法门,那里大家只看生成单例对象的方式。

private synchronized Object getSingletonInstance() {
        if (this.singletonInstance == null) {
            this.targetSource = freshTargetSource();
                        //如果以接口的方式代理对象
            if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
                // Rely on AOP infrastructure to tell us what interfaces to proxy.
                Class<?> targetClass = getTargetClass();
                if (targetClass == null) {
                    throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
                }
                      //获取目标类实现的所有接口,并注册给父类的interfaces属性,为jdk动态代理做准备
                setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
            }
            // Initialize the shared singleton instance.
            super.setFrozen(this.freezeProxy);
                   //这里产生代理对象
            this.singletonInstance = getProxy(createAopProxy());
        }
        return this.singletonInstance;
    }

大家可以见见,暴发代理对象是经过getProxy()方法完成的,那么些艺术我们看一下:

protected Object getProxy(AopProxy aopProxy) {
        return aopProxy.getProxy(this.proxyClassLoader);
    }

AopProxy对象的getProxy()方法暴发大家需求的代办对象,毕竟AopProxy这么些类是什么,大家接下去先看一下发生这几个目的的方法createAopProxy():

protected final synchronized AopProxy createAopProxy() {
        if (!this.active) {
            activate();
        }
        return getAopProxyFactory().createAopProxy(this);
    }

createAopProxy方法:
    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()) {
                return new JdkDynamicAopProxy(config);
            }
            return new ObjenesisCglibAopProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }

Java,在此间大家只看JdkDynamicAopProxy这几个类的兑现,大家前边提到,真正代理对象的转移是由AopProxy的getProxy方法成功的,那里大家看一下JdkDynamicAopProxy的getProxy方法,那也是本文商量的关键:

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);
        findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
        return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
    }

大家看可以很驾驭的观望,代理对象的变动直接采用了jdk动态代理:Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);而代理逻辑是透过完成了InvocationHandler接口的invoke方法落成的。而那边运用的达成了InvocationHandler接口的类就是JdkDynamicAopProxy本身。JdkDynamicAopProxy本身落成了InvocationHandler接口,落成了Spring
AOP拦截器链拦截等一密密麻麻逻辑,大家看一下JdkDynamicAopProxy的invoke方法的切实落到实处:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MethodInvocation invocation;
        Object oldProxy = null;
        boolean setProxyContext = false;

        TargetSource targetSource = this.advised.targetSource;
        Class<?> targetClass = null;
        Object target = null;

        try {
            //没有重写equals方法
            if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
                // The target does not implement the equals(Object) method itself.
                return equals(args[0]);
            }
            //没有重写hashCode方法
            if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
                // The target does not implement the hashCode() method itself.
                return hashCode();
            }
          //代理的类是Advised,这里直接执行,不做任何代理
            if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                    method.getDeclaringClass().isAssignableFrom(Advised.class)) {
                // Service invocations on ProxyConfig with the proxy config...
                return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
            }

            Object retVal;

            if (this.advised.exposeProxy) {
                // Make invocation available if necessary.
                oldProxy = AopContext.setCurrentProxy(proxy);
                setProxyContext = true;
            }

            // May be null. Get as late as possible to minimize the time we "own" the target,
            // in case it comes from a pool.
            //获得代理对象
            target = targetSource.getTarget();
            if (target != null) {
                targetClass = target.getClass();
            }

            // Get the interception chain for this method.
            //获得已经定义的拦截器链
            List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

            // Check whether we have any advice. If we don't, we can fallback on direct
            // reflective invocation of the target, and avoid creating a MethodInvocation.
            if (chain.isEmpty()) {
                // We can skip creating a MethodInvocation: just invoke the target directly
                // Note that the final invoker must be an InvokerInterceptor so we know it does
                // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
                //拦截器链是空的,直接执行需要代理的方法
                retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
            }
            else {
                // We need to create a method invocation...
                //这里是调用拦截器链的地方,先创建一个MethodInvocation对象,然后调用该对象的proceed方法完成拦截器链调用
                invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
                // Proceed to the joinpoint through the interceptor chain.
                retVal = invocation.proceed();
            }

            // Massage return value if necessary.
            Class<?> returnType = method.getReturnType();
            //这里处理返回值,判断返回值和方法需要的返回是否一致
            if (retVal != null && retVal == target && returnType.isInstance(proxy) &&
                    !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
                // Special case: it returned "this" and the return type of the method
                // is type-compatible. Note that we can't help if the target sets
                // a reference to itself in another returned object.
                retVal = proxy;
            } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
                throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);
            }
            return retVal;
        }
        finally {
            if (target != null && !targetSource.isStatic()) {
                // Must have come from TargetSource.
                targetSource.releaseTarget(target);
            }
            if (setProxyContext) {
                // Restore old proxy.
                AopContext.setCurrentProxy(oldProxy);
            }
        }
    }

堵住器链的调用

从上边的代码和注释中咱们得以见到spring已毕aop的重中之重流程,具体如何调用拦截器链,大家来看一下MethodInvocation的proceed方法

public Object proceed() throws Throwable {
        //  We start with an index of -1 and increment early.
        //   currentInterceptorIndex是从-1开始的,所以拦截器链调用结束的时候index是 this.interceptorsAndDynamicMethodMatchers.size() - 1
        //  调用链结束后执行目标方法
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return invokeJoinpoint();
        }
        //  获得当前处理到的拦截器
        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        //  这里判断是否是InterceptorAndDynamicMethodMatcher,如果是,这要判断是否匹配methodMatcher,不匹配则此拦截器不生效
        if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
            // Evaluate dynamic method matcher here: static part will already have
            // been evaluated and found to match.
            InterceptorAndDynamicMethodMatcher dm =
                    (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
            if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
                return dm.interceptor.invoke(this);
            }
            else {
                // Dynamic matching failed.
                // Skip this interceptor and invoke the next in the chain.
                return proceed();
            }
        }
        else {
            // It's an interceptor, so we just invoke it: The pointcut will have
            // been evaluated statically before this object was constructed.
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }

proceed()方法是3个递归方法,我们得以根据代码的诠释知道大概逻辑,InterceptorAndDynamicMethodMatcher的代码如下,我们得以看来,InterceptorAndDynamicMethodMatcher
持有二个MethodInterceptor 对象和一个MethodMatcher
对象,在阻拦器链调用进程中,如若拦截器是InterceptorAndDynamicMethodMatcher
,则会先依据MethodMatcher 判断是还是不是匹配,匹配MethodInterceptor 才会收效。

class InterceptorAndDynamicMethodMatcher {

    final MethodInterceptor interceptor;

    final MethodMatcher methodMatcher;

    public InterceptorAndDynamicMethodMatcher(MethodInterceptor interceptor, MethodMatcher methodMatcher) {
        this.interceptor = interceptor;
        this.methodMatcher = methodMatcher;
    }

}

至于MethodInterceptor 是什么样,MethodInterceptor
的逻辑是怎么着的,我们可以看一下MethodInterceptor
的贰个子类AfterReturningAdviceInterceptor的兑现:

public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {    private final AfterReturningAdvice advice;    /**     * Create a new AfterReturningAdviceInterceptor for the given advice.     * @param advice the AfterReturningAdvice to wrap     */    public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) {        Assert.notNull(advice, "Advice must not be null");        this.advice = advice;    }    @Override    public Object invoke(MethodInvocation mi) throws Throwable {        Object retVal = mi.proceed();        this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());        return retVal;    }}

AfterReturningAdviceInterceptor的功能是在被代理的不二法门重返结果随后添加大家须求的处理逻辑,其落到实处方式大家可以观望,先调用MethodInvocation
的proceed,也等于先两次三番处理拦截器链,等调用落成后执行大家须求的逻辑:this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
到此地,spring使用jdk动态代理落成aop的解析基本上截止,其中拦截器链的调用相比难懂而且相比较根本,需求的同班可以多看看这一块。
在程序员那条路上蒙受瓶颈的情人可以出席群:654675708 大家一块儿来进步发展
但要备注好音信 注!
有Java高级大牛直播讲解知识点,分享文化,有五大专题都是各位老师多年干活经验的梳理和小结,带着大家无微不至、科学地树立和谐的技巧种类和技艺认知
等级一:工程化技术-提高功能 才能有更加多的年华来思考

等级二:源码分析-成为2个内功深厚的程序员

等级三:高品质 分布式 高可用-进入互连网公司不再是您的难点

等级四:质量调优-作者不愿只做五个程序员 小编还有更高的完成

等级五:项目实战-理论与时间执行相结合 你离梦想的偏离只学要你点起脚尖

相关文章