Spring框架学习[创建AOP代理对象并对目标对象切面拦截](九)

2014-11-24 03:05:49 · 作者: · 浏览: 9
{ //为目标对象创建方法回调对象,需要在调用通知之后才调用目标对象的方法 invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain); //调用通知链,沿着通知器链调用所有配置的通知 retVal = invocation.proceed(); } //如果方法有返回值,则将代理对象最为方法返回 if (retVal != null && retVal == target && method.getReturnType().isInstance(proxy) && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) { retVal = proxy; } return retVal; } finally { if (target != null && !targetSource.isStatic()) { //释放目标对象 targetSource.releaseTarget(target); } if (setProxyContext) { //存储代理对象 AopContext.setCurrentProxy(oldProxy); } } }……}

通过上述源码分析,我们看到JdkDynamicAopProxy本身实现了InvocationHandler接口和invoke()方法,JDK的动态代理机制的工作原理是:当调用目标对象的方法时,不是直接调用目标对象,而是首先生成一个目标对象的动态代理对象,触发代理对象的invoke()方法,代理的invoke()方法才会真正调用目标对象的方法。Spring AOP的实现原理是在代理对象invoke()方法调用目标对象的方法时,调用配置的通知。

5.CglibProxyFactory创建AOPProxy代理:

JDK的动态代理只能针对接口生成代理对象,对于没有实现接口的目标对象,必须通过第3方的CGLIB来生成代理对象,CglibProxyFactory创建AOPProxy代理的主要源码如下:

[java] view plaincopyprint //通过CGLIB方式创建AOP代理对象 public Object getProxy(ClassLoader classLoader) { if (logger.isDebugEnabled()) { logger.debug("Creating CGLIB2 proxy: target source is " + this.advised.getTargetSource()); } try { //从代理创建辅助类中获取在IoC容器中配置的目标对象 Class rootClass = this.advised.getTargetClass(); Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy"); //将目标对象本身做为自己的基类 Class proxySuperClass = rootClass; //检查获取到的目标类是否是CGLIB产生的 if (AopUtils.isCglibProxyClass(rootClass)) { //如果目标类是有CGLIB产生的,获取目标类的基类 proxySuperClass = rootClass.getSuperclass(); //获取目标类的接口 Class[] additionalInterfaces = rootClass.getInterfaces(); //将目标类的接口添加到容器AOP代理创建辅助类的配置中 for (Class additionalInterface : additionalInterfaces) { this.advised.addInterface(additionalInterface); } } //校验代理基类 validateClassIfNecessary(proxySuperClass); //配置CGLIB的Enhancer类,Enhancer是CGLIB中的主要操作类 Enhancer enhancer = createEnhancer(); if (classLoader != null) { enhancer.setClassLoader(classLoader); if (classLoader instanceof SmartClassLoader && ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) { enhancer.setUseCache(false); } } //设置enhancer的基类 enhancer.setSuperclass(proxySuperClass); enhancer.setStrategy(new UndeclaredThrowableStrategy(UndeclaredThrowableException.class)); //设置enhancer的接口 enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised)); enhancer.setInterceptDuringConstruction(false); //设置enhancer的回调方法 Callback[] callbacks = getCallbacks(rootClass); enhancer.setCallbacks(callbacks); //将通知器中配置作为enhancer的方法过滤 enhancer.setCallbackFilter(new ProxyCallbackFilter( this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset)); Class[] types = new Class[callbacks.length]; for (int x = 0; x < types.length; x++) { types[x] = callbacks[x].getClass(); } //设置enhancer的回调类型 enhancer.setCallbackTypes(types); //创建代理对象 Object proxy; if (this.constructorArgs != null) { proxy = enhancer.create(this.constructorArgTypes, this.constructorArgs); } else { proxy = enhancer.create(); } return proxy; } 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 (Exception ex) { // TargetSource.getTarget() failed throw new AopConfigException("Unexpected AOP exception", ex); } } //获取给定类的回调通知 private Callback[] getCallbacks(Class rootClass) throws Exception { //优化参数 boolean exposeProxy = this.advised.isExposeProxy(); boolean isFrozen = this.advised.isFrozen(); boolean isStatic = this.advised.getTargetSource().isStatic(); //根据AOP配置创建一个动态通知拦截器,CGLIB创建的动态代理会自动调用 //DynamicAdvisedInterceptor类的intercept方法对目标对象进行拦截处理 Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised); Callback targetInterceptor; //根据是否暴露代理,创建直接应用目标的通知 if (exposeProxy) { targetInterceptor = isStatic new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) : new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()); } else { targetInterceptor = isStatic new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) : new DynamicUnadvisedInterceptor(this.advised.getTargetSource()); } // 创建目标分发器 Callback targetDispatcher = isStatic new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp(); Callback[] mainCallbacks = new Callback[]{ aopInterceptor, //普通通知 targetInterceptor, // 如果优化则不考虑配置的通知 new SerializableNoOp(), //没有被覆盖的方法 targetDispatcher, this.advisedDispatcher, new EqualsInterceptor(this.advised), new HashCodeInterceptor(this.advised) }; Callback[] callbacks; //如果目标是静态的,并且通知链被冻结,则使用优化AOP调用,直接对方法使用 //固定的通知链 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];