Spring的AOP实现方式—ProxyFactoryBean配置方式实现源码剖析

实现Aop功能有两种方式,

1. ProxyFactoryBean方式: 这种方式是通过配置实现

2. ProxyFactory方式:这种方式是通过编程实现

这里只说ProxyFactoryBean方式

首先说下具体的配置,一个例子如下:

  1. <bean id="testAdvisor" class="com.abc.TestAdvisor"  
  2.     <property name="pointcut"  ref="bookPointcut"/>   
  3.         <property name="advice" ref="aroundMethod"></property>  
  4. </bean>  
  5. <bean id="testAop" class="org.springframeword.aop.ProxyFactoryBean">  
  6.       <property name="proxyInterfaces">  
  7.               <value>com.test.AbcInterface</value>  
  8.       </property>  
  9.       <property name="target">  
  10.               <bean class="com.abc.TestTarget"/>  
  11.       </property>  
  12.       <property name="interceptorNames">  
  13.               <list>  
  14.                         <value>testAdvisor</value>    
  15.               </list>  
  16.       </property>  
  17. </bean>  



上述配置中,testAdvisor是配置了一个通知器,该通知器配置了pointcut,即执行该通知需要满足的条件,还配置了匹配条件时要执行的方法,target配置的是要被增强的目标对象,interceptorNames配置的是一些通知,用来增强目标对象。 proxyInterfaces配置的是 需要代理的接口名的字符串数组。如果没有提供,将为目标类使用一个CGLIB代理,即这个接口的配置将会影响是用JDK还是CGLIB来创建目标对象的代理对象。

首先看下ProxyFactoryBean的getObject方法

  1. @Override  
  2.     public Object getObject() throws BeansException {  
  3.         initializeAdvisorChain();  
  4.         //生成代理对象时,因为Spring中有singleton类型和prototype类型这两种不同的Bean,所以要对代理对象的生成做一个区分  
  5.         if (isSingleton()) {  
  6.             //生成singleton的代理对象,这个方法是ProxyFactoryBean生成AOPProxy代理对象的调用入口  
  7.             //代理对象会封装对target目标对象的调用,也就是说针对target对象的方法调用行为会被这里生成的代理对象所拦截  
  8.             return getSingletonInstance();  
  9.         }  
  10.         else {  
  11.             if (this.targetName == null) {  
  12.                 logger.warn("Using non-singleton proxies with singleton targets is often undesirable. " +  
  13.                         "Enable prototype proxies by setting the 'targetName' property.");  
  14.             }  
  15.             return newPrototypeInstance();  
  16.         }  
  17.     }  

这个方法其实就是用来为目标对象生成代理对象的

initializeAdvisorChain是初始化通知器链,即从上述配置中读取interceptorNames参数的值就可以拿到所有为目标对象配置的通知器,该方法的代码如下:
 
 
[html] view plain copy
  1. /**  
  2.      * Create the advisor (interceptor) chain. Advisors that are sourced  
  3.      * from a BeanFactory will be refreshed each time a new prototype instance  
  4.      * is added. Interceptors added programmatically through the factory API  
  5.      * are unaffected by such changes.  
  6.      * 初始化通知器链,通知器链封装了一系列的拦截器,这些拦截器都需要从配置中读取,然后为代理对象的生成做好准备  
  7.      */  
  8.     private synchronized void initializeAdvisorChain() throws AopConfigException, BeansException {  
  9.         //这个标志位是用来表示通知器链是否已经初始化,初始化的工作发生在应用第一次通过ProxyFactoryBean去获取代理对象的时候  
  10.         if (this.advisorChainInitialized) {  
  11.             return;  
  12.         }  
  13.   
  14.         if (!ObjectUtils.isEmpty(this.interceptorNames)) {  
  15.             if (this.beanFactory == null) {  
  16.                 throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +  
  17.                         "- cannot resolve interceptor names " + Arrays.asList(this.interceptorNames));  
  18.             }  
  19.   
  20.             // Globals can't be last unless we specified a targetSource using the property...  
  21.             if (this.interceptorNames[this.interceptorNames.length - 1].endsWith(GLOBAL_SUFFIX) &&  
  22.                     this.targetName == null && this.targetSource == EMPTY_TARGET_SOURCE) {  
  23.                 throw new AopConfigException("Target required after globals");  
  24.             }  
  25.   
  26.             // Materialize interceptor chain from bean names.  
  27.             //这里是添加Advisor链的调用,是通过interceptorNames属性进行配置的  
  28.             //this.interceptorNames就是配置中配置的所有通知器  
  29.             for (String name : this.interceptorNames) {  
  30.                 if (logger.isTraceEnabled()) {  
  31.                     logger.trace("Configuring advisor or advice '" + name + "'");  
  32.                 }  
  33.   
  34.                 if (name.endsWith(GLOBAL_SUFFIX)) {  
  35.                     if (!(this.beanFactory instanceof ListableBeanFactory)) {  
  36.                         throw new AopConfigException(  
  37.                                 "Can only use global advisors or interceptors with a ListableBeanFactory");  
  38.                     }  
  39.                     addGlobalAdvisor((ListableBeanFactory) this.beanFactory,  
  40.                             name.substring(0, name.length() - GLOBAL_SUFFIX.length()));  
  41.                 }  
  42.   
  43.                 else {  
  44.                     // If we get here, we need to add a named interceptor.  
  45.                     // We must check if it's a singleton or prototype.  
  46.                     //如果程序在这里被调用,那么需要加入命名的拦截器advice,并且需要检查这个Bean是singleton还是prototype  
  47.                     Object advice;  
  48.                     if (this.singleton || this.beanFactory.isSingleton(name)) {  
  49.                         // Add the real Advisor/Advice to the chain.  
  50.                         //取得advisor的地方,是通过beanFactory取得的,把intercepNames这个List中的interceptor的名字交给BeanFactory,然后通过getBean去获取  
  51.                         advice = this.beanFactory.getBean(name);  
  52.                     }  
  53.                     else {  
  54.                         // It's a prototype Advice or Advisor: replace with a prototype.  
  55.                         // Avoid unnecessary creation of prototype bean just for advisor chain initialization.  
  56.                         advice = new PrototypePlaceholderAdvisor(name);  
  57.                     }  
  58.                     addAdvisorOnChainCreation(advice, name);  
  59.                 }  
  60.             }  
  61.         }  
  62.   
  63.         this.advisorChainInitialized = true;  
  64.     }  
其他的getSingletonInstance方法和newPrototypeInstance类其实就是构造代理对象
其中getSingletonInstance方法的代码如下:
 
 
[html] view plain copy
  1. private synchronized Object getSingletonInstance() {  
  2.         if (this.singletonInstance == null) {  
  3.             this.targetSource = freshTargetSource();  
  4.             if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {  
  5.                 // Rely on AOP infrastructure to tell us what interfaces to proxy.  
  6.                 //根据AOP框架来判断需要代理的接口  
  7.                 Class<?> targetClass = getTargetClass();  
  8.                 if (targetClass == null) {  
  9.                     throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");  
  10.                 }  
  11.                 //设置代理对象的接口  
  12.                 setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));  
  13.             }  
  14.             // Initialize the shared singleton instance.  
  15.             super.setFrozen(this.freezeProxy);  
  16.             //createAopProxy()方法可能会返回ObjenesisCglibAopProxy对象,也可能会返回JdkDynamicAopProxy对象  
  17.             //然后getProxy方法会根据ObjenesisCglibAopProxy或者JdkDynamicAopProxy对象的getProxy方法来生成最终的代理对象  
  18.             //这就是所谓的,Spring生成代理对象的两种方式,一种是CGLIB,一种是JDK  
  19.             this.singletonInstance = getProxy(createAopProxy());    //这里的方法会使用ProxyFactory来生成需要的Proxy,通过createAopProxy返回的AopProxy来得到代理对象  
  20.         }  
  21.         return this.singletonInstance;  
  22.     }  
注意this.singletonInstance = getProxy(createAopProxy());这行代码
createAopProxy()方法可能会返回ObjenesisCglibAopProxy对象,也可能会返回JdkDynamicAopProxy对象,这个逻辑是在DefaultAopProxyFactory
类中实现的,逻辑如下:

  
  
[html] view plain copy
  1. public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {  
  2.   
  3.     //config里面封装了想要生成的代理对象的信息  
  4.     @Override  
  5.     public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {  
  6.         if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {  
  7.             Class<?> targetClass = config.getTargetClass();   //首先要从AdvisedSupport对象中取得配置的目标对象,如果目标对象为空,则直接抛出异常,因为连目标对象都没有,还为谁创建代理对象  
  8.             if (targetClass == null) {  
  9.                 throw new AopConfigException("TargetSource cannot determine target class: " +  
  10.                         "Either an interface or a target is required for proxy creation.");  
  11.             }  
  12.             //关于AopProxy代理对象的生成,需要考虑使用哪种生成方式,如果目标对象是接口类,那么适合使用JDK来生成代理对象,否则spring会使用CGLIB来生成目标对象的代理对象  
  13.             //对于具体的AopProxy代理对象的生成,最终并不是由DefaultAopProxyFactory来完成,而是分别由JdkDynamicAopProxy和ObjenesisCglibAopProxy完成  
  14.             if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {  
  15.                 return new JdkDynamicAopProxy(config);  //使用JDK来生成AOPProxy代理对象  
  16.             }  
  17.             return new ObjenesisCglibAopProxy(config);  //使用第三方CGLIB来生成AOPProxy代理对象  
  18.         }  
  19.         else {  
  20.             return new JdkDynamicAopProxy(config);  
  21.         }  
  22.     }  
可以看到,它会根据目标类是不是接口等信息来判定使用ObjenesisCglibAopProxy还是JdkDynamicAopProxy

然后getProxy方法会根据ObjenesisCglibAopProxy或者JdkDynamicAopProxy对象的getProxy方法来生成最终的代理对象
这就是所谓的,Spring生成代理对象的两种方式,一种是CGLIB,一种是JDK
下面说说用JdkDynamicAopProxy方式生成的代理对象的拦截方式,它实际用的就是JDK的动态代理
我们知道,动态代理拦截的入口是实现了InvocationHandler接口后的invoke方法,即所有对目标方法的调用首先会被invoke方法拦截
而JdkDynamicAopProxy方式实现的动态代理的拦截入口也是该类的invoke方法,该类的部分方法如下:
 
 
[html] view plain copy
  1. /**  
  2.  * JDK-based {@link AopProxy} implementation for the Spring AOP framework  
  3.  *InvocationHandler接口的invoke方法就是拦截回调的入口,即对目标方法的调用会先被invoke方法拦截,并在invoke方法里面来调用目标方法  
  4.  */  
  5. final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {  
  6.   
  7.     public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {  
  8.         Assert.notNull(config, "AdvisedSupport must not be null");  
  9.         if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {  
  10.             throw new AopConfigException("No advisors and no TargetSource specified");  
  11.         }  
  12.         this.advised = config;  
  13.     }  
  14.   
  15.   
  16.     @Override  
  17.     public Object getProxy() {  
  18.         return getProxy(ClassUtils.getDefaultClassLoader());  
  19.     }  
  20.   
  21.     @Override  
  22.     public Object getProxy(ClassLoader classLoader) {  
  23.         if (logger.isDebugEnabled()) {  
  24.             logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());  
  25.         }  
  26.         //首先从advised对象中取得代理对象的代理接口配置  
  27.         Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);  
  28.         findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);  
  29.         //第三个参数需要实现InvocationHandler接口和invoke方法,这个invoke方法是Proxy代理对象的回调方法  
  30.         //这种方式其实就是用JDK的动态代理来为目标对象创建代理对象,对目标对象方法的调用就是由这个代理对象来调用的  
  31.         return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);  
  32.     }  
  33.   
  34.     /**  
  35.      * Implementation of {@code InvocationHandler.invoke}.  
  36.      * <p>Callers will see exactly the exception thrown by the target,  
  37.      * unless a hook method throws an exception.  
  38.      * 拦截回调入口  
  39.      */  
  40.     @Override  
  41.     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  42.         MethodInvocation invocation;  
  43.         Object oldProxy = null;  
  44.         boolean setProxyContext = false;  
  45.   
  46.         TargetSource targetSource = this.advised.targetSource;  
  47.         Class<?> targetClass = null;  
  48.         Object target = null;  
  49.   
  50.         try {  
  51.             //如果目标对象没有实现Object类的基本方法:equals  
  52.             if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {  
  53.                 // The target does not implement the equals(Object) method itself.  
  54.                 return equals(args[0]);  
  55.             }  
  56.             //如果目标对象没有实现Object类的基本方法:hashcode  
  57.             else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {  
  58.                 // The target does not implement the hashCode() method itself.  
  59.                 return hashCode();  
  60.             }  
  61.             else if (method.getDeclaringClass() == DecoratingProxy.class) {  
  62.                 // There is only getDecoratedClass() declared -> dispatch to proxy config.  
  63.                 return AopProxyUtils.ultimateTargetClass(this.advised);  
  64.             }  
  65.             else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&  
  66.                     method.getDeclaringClass().isAssignableFrom(Advised.class)) {  
  67.                 // Service invocations on ProxyConfig with the proxy config...  
  68.                 //根据代理对象的配置来调用服务  
  69.                 return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);  
  70.             }  
  71.   
  72.             Object retVal;  
  73.   
  74.             if (this.advised.exposeProxy) {  
  75.                 // Make invocation available if necessary.  
  76.                 oldProxy = AopContext.setCurrentProxy(proxy);  
  77.                 setProxyContext = true;  
  78.             }  
  79.   
  80.             // May be null. Get as late as possible to minimize the time we "own" the target,  
  81.             // in case it comes from a pool.  
  82.             //得到目标对象  
  83.             target = targetSource.getTarget();  
  84.             if (target != null) {  
  85.                 targetClass = target.getClass();  
  86.             }  
  87.   
  88.             // Get the interception chain for this method.  获取方法method的拦截器链  
  89.             // 拦截器链实际就是由一系列的Advice通知对象组成的  
  90.             List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);  
  91.   
  92.             // Check whether we have any advice. If we don't, we can fallback on direct  
  93.             // reflective invocation of the target, and avoid creating a MethodInvocation.  
  94.             //如果没有定义拦截器链,就直接调用target对象的对应方法  
  95.             if (chain.isEmpty()) {  
  96.                 // We can skip creating a MethodInvocation: just invoke the target directly  
  97.                 // Note that the final invoker must be an InvokerInterceptor so we know it does  
  98.                 // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.  
  99.                 Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); //适配参数  
  100.                 //调用target对象的对应方法  
  101.                 retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);  
  102.             }  
  103.             else {  
  104.                 // We need to create a method invocation...  
  105.                 //如果有拦截器的设定,那么需要调用拦截器之后才调用目标对象的相应方法,通过构造一个ReflectiveMethodInvocation来实现  
  106.                 invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);  
  107.                 // Proceed to the joinpoint through the interceptor chain.  
  108.                 //沿着拦截器链继续前进  
  109.                 retVal = invocation.proceed();  
  110.             }  
  111.   
  112.             // Massage return value if necessary.  
  113.             Class<?> returnType = method.getReturnType();  
  114.             if (retVal != null && retVal == target && returnType.isInstance(proxy) &&  
  115.                     !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {  
  116.                 // Special case: it returned "this" and the return type of the method  
  117.                 // is type-compatible. Note that we can't help if the target sets  
  118.                 // a reference to itself in another returned object.  
  119.                 retVal = proxy;  
  120.             }  
  121.             else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {  
  122.                 throw new AopInvocationException(  
  123.                         "Null return value from advice does not match primitive return type for: " + method);  
  124.             }  
  125.             return retVal;  
  126.         }  
  127.         finally {  
  128.             if (target != null && !targetSource.isStatic()) {  
  129.                 // Must have come from TargetSource.  
  130.                 targetSource.releaseTarget(target);  
  131.             }  
  132.             if (setProxyContext) {  
  133.                 // Restore old proxy.  
  134.                 AopContext.setCurrentProxy(oldProxy);  
  135.             }  
  136.         }  
  137.     }  
  138.   
  139. }  
上述getProxy方法其实就是JdkDynamicAopProxy用来给目标对象生成代码对象的方法
而invoke就是对目标方法调用时的拦截入口
其中的
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
这行代码就是获取到目标对象所有的拦截器,为什么这里是获取拦截器?其实在上面初始化通知器链的时候拿到的都是配置的通知器,这个方法是要将这些通知器用对应的适配器
适配成对应的拦截器,至于为什么要做这个步骤,在我的另外一篇博客中说的很清楚了,地址如下:

http://blog.csdn.NET/u011734144/article/details/73436539

这里转换成拦截器后,也并不是直接就要将该拦截器加入最终要执行的拦截器链中,还需要判断对应的通知是否应该执行,对应的代码片段如下:

  1. //对配置的advisor通知器进行逐个遍历,这个通知器链都是配置在interceptorNames中的  
  2.         for (Advisor advisor : config.getAdvisors()) {  
  3.             if (advisor instanceof PointcutAdvisor) {  
  4.                 // Add it conditionally.  
  5.                 PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;  
  6.                 if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {  
  7.                     //registry.getInterceptors(advisor)是对从ProxyFactoryBean配置中得到的通知进行适配,从而得到相应的拦截器,再把它加入到前面设置好的list中去  
  8.                     //从而完成所谓的拦截器注册过程  
  9.                     MethodInterceptor[] interceptors = registry.getInterceptors(advisor);  
  10.                     MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();  
  11.                     if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {  
  12.                         if (mm.isRuntime()) {  
  13.                             // Creating a new object instance in the getInterceptors() method  
  14.                             // isn't a problem as we normally cache created chains.  
  15.                             for (MethodInterceptor interceptor : interceptors) {  
  16.                                 interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));  
  17.                             }  
  18.                         }  
  19.                         else {  
  20.                             interceptorList.addAll(Arrays.asList(interceptors));  
  21.                         }  
  22.                     }  
  23.                 }  
  24.             }  
  25.             else if (advisor instanceof IntroductionAdvisor) {  
  26.                 IntroductionAdvisor ia = (IntroductionAdvisor) advisor;  
  27.                 if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {  
  28.                     Interceptor[] interceptors = registry.getInterceptors(advisor);  
  29.                     interceptorList.addAll(Arrays.asList(interceptors));  
  30.                 }  
  31.             }  
  32.             else {  
  33.                 Interceptor[] interceptors = registry.getInterceptors(advisor);  
  34.                 interceptorList.addAll(Arrays.asList(interceptors));  
  35.             }  
  36.         }  

这里需要判断通知器中配置的切入点是否匹配当前要被调用的方法,即 MethodMatchers.matches是否为true,只有匹配的通知才会将对应的拦截器加入到最终待执行的拦截器链中


接下来invoke方法中比较核心的就是如下代码:

  1. retVal = invocation.proceed();  
这个方法其实就是启动拦截器链的执行,依次执行每一个拦截器链,在每一个拦截器里面都会根据通知的类型来决定是先执行通知的方法还是先继续执行下一个拦截器,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值