Spring AOP实现声明式事务代码分析

简介:

 众所周知,Spring的声明式事务是利用AOP手段实现的,所谓“深入一点,你会更快乐”,本文试图给出相关代码分析。

  AOP联盟为增强定义了org.aopalliance.aop.Advice接口,Spring由Advice接口扩展了5中类型的增强(接口),AOP联盟自身提供了IntroductionInterceptor->MethodInterceptor->Interceptor->Advice,而MethodInterceptor就代表环绕增强,表示在目标方法执行前后实施增强。要进行事务操作,正是要在目标方法前后加入相应的代码,因此,Spring为我们提供了TransactionInterceptor类。

  TransactionInterceptor的invoke方法调用了父类TransactionAspectSupport的invokeWithinTransactionf方法,

 

Java代码   收藏代码
  1. if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {  
  2.             // Standard transaction demarcation with getTransaction and commit/rollback calls.  
  3.             TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);  
  4.             Object retVal = null;  
  5.             try {  
  6.                 // This is an around advice: Invoke the next interceptor in the chain.  
  7.                 // This will normally result in a target object being invoked.  
  8.                 retVal = invocation.proceedWithInvocation();  
  9.             }  
  10.             catch (Throwable ex) {  
  11.                 // target invocation exception  
  12.                 completeTransactionAfterThrowing(txInfo, ex);  
  13.                 throw ex;  
  14.             }  
  15.             finally {  
  16.                 cleanupTransactionInfo(txInfo);  
  17.             }  
  18.             commitTransactionAfterReturning(txInfo);  
  19.             return retVal;  
  20.         }  

 瞬间,我们看到了我们期望看到的代码,其中completeTransactionAfterThrowing里面做的是rollback的相关操作。

 

  Spring 提供了多种不同的方案实现对 bean 的 aop proxy, 包括 ProxyFactoryBean, 便利的 TransactionProxyFactoryBean 以及 AutoProxyCreator 等,

这里重点说一下最常用的 ProxyFactoryBean, TransactionProxyFactoryBean, BeanNameAutoProxyCreator, DefaultAdvisorAutoProxyCreator 的联系和区别   

  

1. ProxyFactoryBean : 使用率最高的 proxy 方式, 它通过配置 interceptorNames 属性决定加入哪些 advisor (method interceptor 将会被自动包装成 advisor),   

注意是 "interceptorNames" 而不是 "interceptors", 

原因是 ProxyFactoryBean 可能返回非 singleton 的 proxy 实例, 而 advisior 可能也是非 singleton 的, 

因此不能通过 interceptor reference 来注入   

  

2. TransactionProxyFactoryBean : 特定用于 transaction proxy, 注意其 super class 是 AbstractSingletonProxyFactoryBean, 也就是说,

TransactionProxyFactoryBean 永远无法返回非 singleton 的 proxy 实例 !

如果你需要非 singleton 的 proxy 实例, 请考虑使用 ProxyFactoryBean.   

  

3. BeanNameAutoProxyCreator : 故名思义, 根据 bean name 进行 auto proxy, bean name 的 match 规则参见 org.springframework.util.PatternMatchUtils   

  

4. DefaultAdvisorAutoProxyCreator : 更强大的 auto proxy creator, 强大之处在于它会 cahce 容器中所有注册的 advisor, 然后搜索容器中所有的 bean ,   

如果某个 bean 满足 advisor 中的 Pointcut, 那么将会被自动代理, 与 BeanNameAutoProxyCreator 相比, 省去了配置 beanNames 的工作, 

 

5. AnnotationAwareAspectJAutoProxyCreator -> @Aspect  <aop:aspectj-autoproxy/>

  -> @Transactinal <tx:annotation-driven transaction-manager="txManager"/>

 

 AbstractAutoProxyCreator实现了BeanPostProcessor,Spring默认会自动创建代理。

Java代码   收藏代码
  1. // AbstractAutowireCapableBeanFactory  
  2. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)  
  3.             throws BeansException {  
  4.   
  5.         Object result = existingBean;  
  6.         for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {  
  7.             result = beanProcessor.postProcessBeforeInitialization(result, beanName);  
  8.             if (result == null) {  
  9.                 return result;  
  10.             }  
  11.         }  
  12.         return result;  
  13.     }  
  14.   
  15.     public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)  
  16.             throws BeansException {  
  17.   
  18.         Object result = existingBean;  
  19.         for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {  
  20.             result = beanProcessor.postProcessAfterInitialization(result, beanName);  
  21.             if (result == null) {  
  22.                 return result;  
  23.             }  
  24.         }  
  25.         return result;  
  26.     }  

 

 

我们来看下AbstractAutoProxyCreator里的重点代码

Java代码   收藏代码
  1. // AbstractAutoProxyCreator  
  2. public Object postProcessBeforeInitialization(Object bean, String beanName) {  
  3.         return bean;  
  4.     }  
  5.   
  6.     /** 
  7.      * Create a proxy with the configured interceptors if the bean is 
  8.      * identified as one to proxy by the subclass. 
  9.      * @see #getAdvicesAndAdvisorsForBean 
  10.      */  
  11.     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {  
  12.         if (bean != null) {  
  13.             Object cacheKey = getCacheKey(bean.getClass(), beanName);  
  14.             if (!this.earlyProxyReferences.contains(cacheKey)) {  
  15.                 return wrapIfNecessary(bean, beanName, cacheKey);  
  16.             }  
  17.         }  
  18.         return bean;  
  19.     }  

 

Java代码   收藏代码
  1. /** 
  2.      * Wrap the given bean if necessary, i.e. if it is eligible for being proxied. 
  3.      * @param bean the raw bean instance 
  4.      * @param beanName the name of the bean 
  5.      * @param cacheKey the cache key for metadata access 
  6.      * @return a proxy wrapping the bean, or the raw bean instance as-is 
  7.      */  
  8.     protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {  
  9.         if (this.targetSourcedBeans.contains(beanName)) {  
  10.             return bean;  
  11.         }  
  12.         if (this.nonAdvisedBeans.contains(cacheKey)) {  
  13.             return bean;  
  14.         }  
  15.         if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {  
  16.             this.nonAdvisedBeans.add(cacheKey);  
  17.             return bean;  
  18.         }  
  19.   
  20.         // Create proxy if we have advice.  
  21.         Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);  
  22.         if (specificInterceptors != DO_NOT_PROXY) {  
  23.                  // 有AnnotationAwareAspectJAutoProxyCreator 这个processor时  
  24.             this.advisedBeans.add(cacheKey);  
  25.             Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));  
  26.             this.proxyTypes.put(cacheKey, proxy.getClass());  
  27.             return proxy;  
  28.         }  
  29.   
  30.         this.nonAdvisedBeans.add(cacheKey);  
  31.         return bean;  
  32.     }  

 

 

Java代码   收藏代码
  1. protected Object createProxy(  
  2.             Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {  
  3.   
  4.         ProxyFactory proxyFactory = new ProxyFactory();  
  5.         // Copy our properties (proxyTargetClass etc) inherited from ProxyConfig.  
  6.         proxyFactory.copyFrom(this);  
  7.   
  8.         if (!shouldProxyTargetClass(beanClass, beanName)) {  
  9.             // Must allow for introductions; can't just set interfaces to  
  10.             // the target's interfaces only.  
  11.             Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader);  
  12.             for (Class<?> targetInterface : targetInterfaces) {  
  13.                 proxyFactory.addInterface(targetInterface);  
  14.             }  
  15.         }  
  16.   
  17.         Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);  
  18.         for (Advisor advisor : advisors) {  
  19.             proxyFactory.addAdvisor(advisor);  
  20.         }  
  21.   
  22.         proxyFactory.setTargetSource(targetSource);  
  23.         customizeProxyFactory(proxyFactory);  
  24.   
  25.         proxyFactory.setFrozen(this.freezeProxy);  
  26.         if (advisorsPreFiltered()) {  
  27.             proxyFactory.setPreFiltered(true);  
  28.         }  
  29.   
  30.         return proxyFactory.getProxy(this.proxyClassLoader);  
  31.     }  

 

至于事务切面和其他切面形成切面chain时的调用关系,请参考http://wely.iteye.com/blog/2313924的解释。

  本文并未介绍事务属性、事务状态、事务管理器以及事务自身更底层的一些内容,这些内容留待我们研究了mysql的事务后再详细介绍。


原文链接:[http://wely.iteye.com/blog/2317428]

相关文章
|
22天前
|
设计模式 Java Maven
Spring Aop 底层责任链思路实现-springaopdi-ceng-ze-ren-lian-si-lu-shi-xian
Spring Aop 底层责任链思路实现-springaopdi-ceng-ze-ren-lian-si-lu-shi-xian
31 1
|
15天前
|
XML Java Maven
Spring之Aop的注解使用
Spring之Aop的注解使用
|
21天前
|
Java Spring
Spring 如何实现 AOP
Spring 如何实现 AOP
17 0
|
30天前
|
Java 编译器 程序员
Spring AOP 和 AspectJ 的比较
Spring AOP 和 AspectJ 的比较
34 0
|
1月前
|
Java Spring
【spring(三)】AOP总结
【spring(三)】AOP总结
|
10月前
|
XML Java 测试技术
【Spring学习笔记 九】Spring声明式事务管理实现机制(下)
【Spring学习笔记 九】Spring声明式事务管理实现机制(下)
57 0
|
10月前
|
NoSQL Java 关系型数据库
【Spring学习笔记 九】Spring声明式事务管理实现机制
【Spring学习笔记 九】Spring声明式事务管理实现机制
55 0
|
10月前
|
Java 数据库连接 API
请解释Spring中的声明式事务管理是如何工作的?
在Spring框架中,声明式事务管理是通过使用AOP(面向切面编程)和事务拦截器来实现的。声明式事务管理允许开发者通过在方法或类级别上添加注解来定义事务的行为,而无需显式地编写事务管理的代码。
请解释Spring中的声明式事务管理是如何工作的?
|
XML Java 数据库
Spring学习(十二):声明式事务管理(完全响应式)
Spring学习(十二):声明式事务管理(完全响应式)
123 0
|
Java 数据库 Spring
Spring学习(十一):声明式事务管理(响应式)
什么是事务:事务是数据库操作的最基本单元,逻辑上一组操作,要么都成功,如果有一个失败则意味着所有操作都失败
130 0
Spring学习(十一):声明式事务管理(响应式)