版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Spring声明式事务管理源码解读之事务提交 简介:上次说到spring声明式事务管理的事务开始部分,按流程来讲,下面应该提交事务了, spring的声明式事务管理其实是比较复杂的,事实上这种复杂性正是由于事务本身的复杂性导致的,如果能用两三句话就把这部分内容说清楚是不现实的,也是不成熟的,而我对这部分的理解也可能是不全面的,还是那句话,希望大家和我一起把本贴的质量提交起来。 在下面的文章中,我讲会多次提到第一篇文章,第一篇文章的地址是:/topic/87426 如果要理解事务提交的话,理解事务开始是一个前提条件,所以请先看第一篇文章,再来看这篇 如果
2、你仔细看下去,我想肯定是有很多收获,因为我们确实能从spring的代码和思想中学到很多东西。 正文: 其实俺的感觉就是事务提交要比事务开始复杂,看事务是否提交我们还是要回到TransactionInterceptor类的invoke方法 Java代码 public Object invoke(MethodInvocation invocation) throws Throwable / Work out the target class: may be <code>null</code>. / The TransactionAttributeSource should
3、be passed the target class / as well as the method, which may be from an interface Class targetClass = (invocation.getThis() != null) ? invocation.getThis().getClass() : null; / Create transaction if necessary. TransactionInfo txInfo = createTransactionIfNecessary(invocation.getMethod(), targetClass
4、); Object retVal = null; try / This is an around advice. / Invoke the next interceptor in the chain. / This will normally result in a target object being invoked. retVal = ceed(); catch (Throwable ex) / target invocation exception doCloseTransactionAfterThrowing(txInfo, ex); throw ex;
5、finally doFinally(txInfo);/业务方法出栈后必须先执行的一个方法 doCommitTransactionAfterReturning(txInfo); return retVal; public Object invoke(MethodInvocation invocation) throws Throwable / Work out the target class: may be <code>null</code>./ The TransactionAttributeSource should be passed the target cla
6、ss/ as well as the method, which may be from an interfaceClass targetClass = (invocation.getThis() != null) ? invocation.getThis().getClass() : null;/ Create transaction if necessary.TransactionInfo txInfo = createTransactionIfNecessary(invocation.getMethod(), targetClass);Object retVal = null;try /
7、 This is an around advice./ Invoke the next interceptor in the chain./ This will normally result in a target object being invoked.retVal = ceed();catch (Throwable ex) / target invocation exceptiondoCloseTransactionAfterThrowing(txInfo, ex);throw ex;finally doFinally(txInfo);/业务方法出栈后必须先
8、执行的一个方法doCommitTransactionAfterReturning(txInfo);return retVal;其中的doFinally(txInfo)那一行很重要,也就是说不管如何,这个doFinally方法都是要被调用的,为什么它这么重要呢,举个例子: 我们还是以propregation_required来举例子吧,假设情况是这样的,AService中有一个方法调用了BService中的,这两个方法都处在事务体之中,他们的传播途径都是required。那么调用开始了,AService的方法首先入方法栈,并创建了TransactionInfo的实例,接着BService的方法入
9、栈,又创建了一个TransactionInfo的实例,而重点要说明的是TransactionInfo是一个自身关联的内部类,第二个方法入栈时,会给新创建的TransactionInfo的实例设置一个属性,就是TransactionInfo对象中的private TransactionInfo oldTransactionInfo;属性,这个属性表明BService方法的创建的TransactionInfo对象是有一个old的transactionInfo对象的,这个oldTransactionInfo对象就是AService方法入栈时创建的TransactionInfo对象,我们还记得在cre
10、ateTransactionIfNecessary方法里有这样一个方法吧: Java代码 protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) / We always bind the TransactionInfo to the thread, even if we didnt create / a new transaction here. This guarantees that the TransactionInfo stack / will be managed
11、 correctly even if no transaction was created by this aspect. txInfo.bindToThread(); return txInfo; 就是这个bindToThread()方法在作怪: private void bindToThread() / Expose current TransactionStatus, preserving any existing transactionStatus for / restoration after this transaction is complete. oldTransactionI
12、nfo = (TransactionInfo) currentTransactionInfo.get(); currentTransactionInfo.set(this); protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) / We always bind the TransactionInfo to the thread, even if we didnt create/ a new transaction here. This guarantees that t
13、he TransactionInfo stack/ will be managed correctly even if no transaction was created by this aspect.txInfo.bindToThread();return txInfo;就是这个bindToThread()方法在作怪:private void bindToThread() / Expose current TransactionStatus, preserving any existing transactionStatus for/ restoration after this tran
14、saction is complete.oldTransactionInfo = (TransactionInfo) currentTransactionInfo.get();currentTransactionInfo.set(this);如果当前线程中已经有了一个TransactionInfo,则拿出来放到新建的transactionInfo对象的oldTransactionInfo属性中,然后再把新建的TransactionInfo设置到当前线程中。 这里有一个概念要搞清楚,就是TransactionInfo对象并不是表明事务状态的对象,表明事务状态的对象是TransactionStat
15、us对象,这个对象同样是TransactionInfo的一个属性(这一点,我在前面一篇文章中并没有讲清楚)。 接下来BService中的那个方法返回,那么该它退栈了,它退栈后要做的就是doFinally方法,即把它的oldTransactionInfo设置到当前线程中(这个TransactionInfo对象显然就是AService方法入栈时创建的,怎么现在又要设置到线程中去呢,原因就是BService的方法出栈时并不提交事务,因为BService的传播途径是required,所以要把栈顶的方法所创建transactioninfo给设置到当前线程中),即调用AService的方法时所创建的Tra
16、nsactionInfo对象。那么在AServie的方法出栈时同样会设置TransactionInfo对象的oldTransactionInfo到当前线程,这时候显然oldTransactionInfo是空的,但AService中的方法会提交事务,所以它的oldTransactionInfo也应该是空了。 在这个小插曲之后,么接下来就应该是到提交事务了,之前在AService的方法出栈时,我们拿到了它入栈时创建的TransactionInfo对象,这个对象中包含了AService的方法事务状态。即TransactionStatus对象,很显然,太显然了,事务提交中的任何属性都和事务开始时的创建
17、的对象息息相关,这个TransactionStatus对象哪里来的,我们再回头看看createTransactionIfNessary方法吧: Java代码 protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) txInfo.newTransactionStatus(this.transactionManager.getTransaction(txAttr); protected TransactionInfo createTransactionIfNecessary(M
18、ethod method, Class targetClass) txInfo.newTransactionStatus(this.transactionManager.getTransaction(txAttr);再看看transactionManager.getTransaction(txAttr)方法吧: Java代码 public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException else if (definition.getPropa
19、gationBehavior() = TransactionDefinition.PROPAGATION_REQUIRED | definition.getPropagationBehavior() = TransactionDefinition.PROPAGATION_REQUIRES_NEW | definition.getPropagationBehavior() = TransactionDefinition.PROPAGATION_NESTED) if (debugEnabled) logger.debug(Creating new transaction with name + d
20、efinition.getName() + ); doBegin(transaction, definition); boolean newSynchronization = (this.transactionSynchronization != SYNCHRONIZATION_NEVER); return newTransactionStatus(definition, transaction, true, newSynchronization, debugEnabled, null);/注意这里的返回值,返回的就是一个TransactionStatus对象,这个对象表明了一个事务的状态,比
21、如说是否是一个新的事务,事务是否已经结束,等等,这个对象是非常重要的,在事务提交的时候还是会用到它的。 public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException else if (definition.getPropagationBehavior() = TransactionDefinition.PROPAGATION_REQUIRED |definition.getPropagationBehavior() = Transaction
22、Definition.PROPAGATION_REQUIRES_NEW |definition.getPropagationBehavior() = TransactionDefinition.PROPAGATION_NESTED) if (debugEnabled) logger.debug(Creating new transaction with name + definition.getName() + );doBegin(transaction, definition);boolean newSynchronization = (this.transactionSynchroniza
23、tion != SYNCHRONIZATION_NEVER);return newTransactionStatus(definition, transaction, true, newSynchronization, debugEnabled, null);/注意这里的返回值,返回的就是一个TransactionStatus对象,这个对象表明了一个事务的状态,比如说是否是一个新的事务,事务是否已经结束,等等,这个对象是非常重要的,在事务提交的时候还是会用到它的。 还有一点需要说明的是,AService的方法在执行之前创建的transactionstatus确实是通过这个方法创建的,但是,BS
24、ervice的方法在执行之前创建transactionstatus的方法就与这个不一样了,下面会有详解。 回顾了事务开始时所调用的方法之后,是不是觉得现在对spring如何处理事务越来越清晰了呢。由于这么几个方法的调用,每个方法入栈之前它的事务状态就已经被设置好了。这个事务状态就是为了在方法出栈时被调用而准备的。 让我们再次回到BService中的方法出栈的那个时间段,看看spring都做了些什么,我们知道,后入栈的肯定是先出栈,BService中的方法后入栈,拿它肯定要先出栈了,它出栈的时候是要判断是否要提交事务,释放资源的,让我们来看看TransactionInterceptor的invo
25、ke的最后那个方法doCommitTransactionAfterReturning: Java代码 protected void doCommitTransactionAfterReturning(TransactionInfo txInfo) if (txInfo != null && txInfo.hasTransaction() if (logger.isDebugEnabled() logger.debug(Invoking commit for transaction on + txInfo.joinpointIdentification(); this.trans
26、actionMmit(txInfo.getTransactionStatus(); /瞧:提交事务时用到了表明事务状态的那个TransactionStatus对象了。 protected void doCommitTransactionAfterReturning(TransactionInfo txInfo) if (txInfo != null && txInfo.hasTransaction() if (logger.isDebugEnabled() logger.debug(Invoking commit for transaction on + t
27、xInfo.joinpointIdentification();this.transactionMmit(txInfo.getTransactionStatus();/瞧:提交事务时用到了表明事务状态的那个TransactionStatus对象了。看这个方法的名字就知道spring是要在业务方法出栈时提交事务,貌似很简单,但是事实是这样的吗? 我们接着往下看。 Java代码 public final void commit(TransactionStatus status) throws TransactionException DefaultTransactionStat
28、us defStatus = (DefaultTransactionStatus) status; if (defStatus.isCompleted() throw new IllegalTransactionStateException( Transaction is already completed - do not call commit or rollback more than once per transaction); if (defStatus.isLocalRollbackOnly() if (defStatus.isDebug() logger.debug(Transa
29、ctional code has requested rollback); processRollback(defStatus); return; if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly() if (defStatus.isDebug() logger.debug(Global transaction is marked as rollback-only but transactional code requested commit); processRollback(d
30、efStatus); throw new UnexpectedRollbackException( Transaction has been rolled back because it has been marked as rollback-only); processCommit(defStatus); public final void commit(TransactionStatus status) throws TransactionException DefaultTransactionStatus defStatus = (DefaultTransactionStatus) st
31、atus;if (defStatus.isCompleted() throw new IllegalTransactionStateException(Transaction is already completed - do not call commit or rollback more than once per transaction);if (defStatus.isLocalRollbackOnly() if (defStatus.isDebug() logger.debug(Transactional code has requested rollback);processRol
32、lback(defStatus);return;if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly() if (defStatus.isDebug() logger.debug(Global transaction is marked as rollback-only but transactional code requested commit);processRollback(defStatus);throw new UnexpectedRollbackException(Tra
33、nsaction has been rolled back because it has been marked as rollback-only);processCommit(defStatus);上面这段代码就是transactionmanager中的commit,但是看上去,它又把自己的职责分配给别人了,从代码里我们看到,如果事务已经结束了就抛异常,如果事务是rollbackonly的,那么就rollback吧,但是按照正常流程,我们还是想来看一下,事务的提交,就是processCommit(status)这个方法吧。 Java代码 private void processCommit(
34、DefaultTransactionStatus status) throws TransactionException try boolean beforeCompletionInvoked = false; try triggerBeforeCommit(status); triggerBeforeCompletion(status); beforeCompletionInvoked = true; if (status.hasSavepoint() if (status.isDebug() logger.debug(Releasing transaction savepoint); st
35、atus.releaseHeldSavepoint(); else if (status.isNewTransaction() /这个判断非常重要,下面会详细讲解这个判断的作用 if (status.isDebug() logger.debug(Initiating transaction commit); boolean globalRollbackOnly = status.isGlobalRollbackOnly(); doCommit(status); / Throw UnexpectedRollbackException if we have a global rollback-on
36、ly / marker but still didnt get a corresponding exception from commit. private void processCommit(DefaultTransactionStatus status) throws TransactionException try boolean beforeCompletionInvoked = false;try triggerBeforeCommit(status);triggerBeforeCompletion(status);beforeCompletionInvoked = true;if
37、 (status.hasSavepoint() if (status.isDebug() logger.debug(Releasing transaction savepoint);status.releaseHeldSavepoint();else if (status.isNewTransaction() /这个判断非常重要,下面会详细讲解这个判断的作用if (status.isDebug() logger.debug(Initiating transaction commit);boolean globalRollbackOnly = status.isGlobalRollbackOnl
38、y();doCommit(status);/ Throw UnexpectedRollbackException if we have a global rollback-only/ marker but still didnt get a corresponding exception from commit.我们注意到,在判断一个事务是否是新事务之前还有一个status.hasSavepoint()的判断,我认为这个判断事实上就是嵌套事务的判断,即判断这个事务是否是嵌套事务,如果不是嵌套事务,则再判断它是否是一个新事务,下面这段话就非常重要了,BService的中的方法是先出栈的,也就是说
39、在调用BService之前的创建的那个事务状态对象在这里要先被判断,但是由于在调用BService的方法之前已经创建了一个Transaction和Session(假设我们使用的是hibernate3),这时候在创建第二个TransactionInfo(再强调一下吧,TransactionInfo并不是Transaction,Transaction是真正的事务对象,TransactionInfo只不过是一个辅助类而已,用来记录一系列状态的辅助类)的TransactionStatus的时候就会进入下面这个方法(当然在这之前会判断一下当前线程中是否已经有了一个SessionHolder对象,不清楚S
40、essionHolder作用的同学情况第一篇文章),这个方法其实应该放到第一篇文章中讲的,但是想到如果不讲事务提交就讲这个方法好像没有这么贴切,废话少说,我们来看一下吧: Java代码 private TransactionStatus handleExistingTransaction( TransactionDefinition definition, Object transaction, boolean debugEnabled) throws TransactionException if (definition.getPropagationBehavior() = Transact
41、ionDefinition.PROPAGATION_NEVER) throw new IllegalTransactionStateException( Transaction propagation never but existing transaction found); if (definition.getPropagationBehavior() = TransactionDefinition.PROPAGATION_NOT_SUPPORTED) if (debugEnabled) logger.debug(Suspending current transaction); Objec
42、t suspendedResources = suspend(transaction); boolean newSynchronization = (this.transactionSynchronization = SYNCHRONIZATION_ALWAYS); return newTransactionStatus( definition, null, false, newSynchronization, debugEnabled, suspendedResources); if (definition.getPropagationBehavior() = TransactionDefi
43、nition.PROPAGATION_REQUIRES_NEW) if (debugEnabled) logger.debug(Suspending current transaction, creating new transaction with name + definition.getName() + ); Object suspendedResources = suspend(transaction); doBegin(transaction, definition); boolean newSynchronization = (this.transactionSynchroniza
44、tion != SYNCHRONIZATION_NEVER); return newTransactionStatus( definition, transaction, true, newSynchronization, debugEnabled, suspendedResources); if (definition.getPropagationBehavior() = TransactionDefinition.PROPAGATION_NESTED) if (!isNestedTransactionAllowed() throw new NestedTransactionNotSuppo
45、rtedException( Transaction manager does not allow nested transactions by default - + specify nestedTransactionAllowed property with value true); if (debugEnabled) logger.debug(Creating nested transaction with name + definition.getName() + ); if (useSavepointForNestedTransaction() / Create savepoint
46、within existing Spring-managed transaction, / through the SavepointManager API implemented by TransactionStatus. / Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization. DefaultTransactionStatus status = newTransactionStatus(definition, transaction, false, false, debugEnabled, nul
47、l); status.createAndHoldSavepoint(); return status; else / Nested transaction through nested begin and commit/rollback calls. / Usually only for JTA: Spring synchronization might get activated here / in case of a pre-existing JTA transaction. doBegin(transaction, definition); boolean newSynchronizat
48、ion = (this.transactionSynchronization != SYNCHRONIZATION_NEVER); return newTransactionStatus(definition, transaction, true, newSynchronization, debugEnabled, null); / Assumably PROPAGATION_SUPPORTS. if (debugEnabled) logger.debug(Participating in existing transaction); boolean newSynchronization =
49、(this.transactionSynchronization != SYNCHRONIZATION_NEVER); return newTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null); private TransactionStatus handleExistingTransaction(TransactionDefinition definition, Object transaction, boolean debugEnabled)throws TransactionException if (definition.getPropagationBehavior() = TransactionDefin
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 九年级音乐“非洲灵感”主题单元教学设计
- 初中数学八年级下册统计图教学设计
- 高中信息技术高二选择性必修《数据与数据结构》教学设计:组合数据类型的建模与实现
- 小学信息技术六年级“自动熄灭转向灯”跨学科教学设计
- 高二英语选择性必修第一册Unit 1 Welcome to the unit词汇默写与导入教学设计
- 小学一年级劳动课七巧板创意拼搭教学设计
- 九年级数学教学设计:用配方法解较简单的一元二次方程
- 2.2.2 脊椎动物(鱼)教学设计(初中生物七年级上册)
- 初中九年级数学教学设计:二次函数图象求一元二次方程根的近似值
- 2026事业单位工勤技能-新疆-新疆家禽饲养员四级(中级工)历年参考题库含答案详解
- 统编版语文七年级上册期末基础知识复习提纲
- 2026年铁路局招聘铁路基础知识考试试题库及答案
- 华兴数控WA-32XTA用户手册
- 年产1亿片盐酸二甲双胍缓释片生产工艺设计
- 《结直肠癌的治疗进展》课件
- 《亲子沟通模式对幼儿情绪调节能力的影响探究国内外文献综述》1600字
- 《有效团队管理培训》课件
- DB11∕T 1655-2019 危险化学品企业装置设施拆除安全管理规范
- JB-T 8532-2023 脉冲喷吹类袋式除尘器
- 《测绘管理法律与法规》课件-测绘资质管理
- JGT14-2010 通风空调风口
评论
0/150
提交评论