SpringAOP中的动态代理

Spring代理实际上是对JDK代理和CGLIB代理做了一层封装,并且引入了AOP概念:Aspect、advice、joinpoint等等,同时引入了AspectJ中的一些注解@pointCut,@after,@before等等.Spring Aop严格的来说都是动态代理,和Aspectj的关系并不大。

Spring代理中org.springframework.aop.framework.ProxyFactory是关键,一个简单的使用API编程的Spring AOP代理如下:

ProxyFactory proxyFactory =new ProxyFactory(Calculator.class, new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                return null;
            }
        });
        proxyFactory.setOptimize(false);
        //得到代理对象
        proxyFactory.getProxy();

在调用getProxy()时,会优先得到一个默认的DefaultAopProxyFactory.这个类主要是决定到底是使用JDK代理还是CGLIB代理:

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        //optimize 优化,如上列代码编程true会默认进入if
        //ProxyTargetClass 是否对具体类进行代理
        //判断传入的class 是否有接口。如果没有也会进入选择
        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.");
            }
            //如果目标是接口的话还是默认使用JDK
            if (targetClass.isInterface()) {
                return new JdkDynamicAopProxy(config);
            }
            return CglibProxyFactory.createCglibProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }

可以看见一些必要的信息,我们在使用Spring AOP的时候通常会在XML配置文件中设置 来使用CGlib代理。现在我们可以发现只要三个参数其中一个为true,便可以有机会选择使用CGLIB代理。但是是否一定会使用还是得看传入的class到底是个怎样的类。如果是接口,就算开启了这几个开关,最后还是会自动选择JDK代理。

JdkDynamicAopProxy这个类实现了InvokeHandler接口,最后调用getProxy():

public Object getProxy(ClassLoader classLoader) {
        //...
        //返回代理对象
        return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
    }

那么JdkDynamicAopProxy中的invoke方法就是最核心的方法了(实现了InvokeHandler接口):

/**
     * Implementation of {@code InvocationHandler.invoke}.
     * 

Callers will see exactly the exception thrown by the target, * unless a hook method throws an exception. */ 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和hashCode,否则不代理。因为JDK代理会默认代理这两个方法 if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) { return equals(args[0]); } if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) { return hashCode(); } //不能代理adviser接口和子接口自身 if (!this.advised.opaque && method.getDeclaringClass().isInterface() && method.getDeclaringClass().isAssignableFrom(Advised.class)) { return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args); } Object retVal; //代理类和ThreadLocal绑定 if (this.advised.exposeProxy) { // Make invocation available if necessary. oldProxy = AopContext.setCurrentProxy(proxy); setProxyContext = true; } //合一从TargetSource得到一个实例对象,可实现接口获得 target = targetSource.getTarget(); if (target != null) { targetClass = target.getClass(); } //得到拦截器链 List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); //如果没有定义拦截器链。直接调用方法不进行代理 if (chain.isEmpty()) { retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args); } else { // We need to create a method invocation... invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain); //执行拦截器链。通过proceed递归调用 // 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())) { //如果返回值是this 直接返回代理对象本身 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()) { targetSource.releaseTarget(target); } if (setProxyContext) { AopContext.setCurrentProxy(oldProxy); } } }

下面来分析整个代理的拦截器是怎么运行的,ReflectiveMethodInvocation这个类的proceed()方法负责递归调用所有的拦截的织入。

public Object proceed() throws Throwable {
        //list的索引从-1开始。 
                if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
        //所有interceptor都被执行完了,直接执行原方法
            return invokeJoinpoint();
        }
        //得到一个interceptor。不管是before还是after等织入,都不受在list中的位置影响。
        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        //....
        //调用invoke方法
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }

需要注意的是invoke方法中传入的是this。在MethodInvocation中又可以调用procced来实现递归调用。比如像下面这样:

new MethodInterceptor() {
            @Override
public Object invoke(MethodInvocation invocation) throws Throwable {
              Object re= invocation.proceed();
              return re;
            }
        }

那么要实现织入,只需要控制织入的代码和调用proceed方法的位置,在Spring中的before织入是这样实现的:

public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {
 
    private MethodBeforeAdvice advice;
 
    public Object invoke(MethodInvocation mi) throws Throwable {
        //调用before实际代码
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
        //继续迭代
        return mi.proceed();
    }

afterRuturning是这样实现的:

public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {
 
    private final AfterReturningAdvice advice;
 
    public Object invoke(MethodInvocation mi) throws Throwable {
        Object retVal = mi.proceed();
        //只要控制和mi.proceed()调用的位置关系就可以实现任何状态的织入效果
        this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
        return retVal;
    }

总结:
Spring AOP封装了JDK和CGLIB的动态代理实现,同时引入了AspectJ的编程方式和注解。使得可以使用标准的AOP编程规范来编写代码外,还提供了多种代理方式选择。可以根据需求来选择最合适的代理模式。同时Spring也提供了XML配置的方式实现AOP配置。可以说是把所有想要的都做出来了,Spring是在平时编程中使用动态代理的不二选择.

你可能感兴趣的:(SpringAOP中的动态代理)