2024年5月31日发(作者:)

Spring事务原理

统观spring事务,围绕着两个核心PlatformTransactionManager和TransactionStatus

spring提供了几个关于事务处理的类:

TransactionDefinition //事务属性定义

TranscationStatus //代表了当前的事务,可以提交,回滚。

PlatformTransactionManager这个是spring提供的用于管理事务的基础接口,其下有一个实现的抽象类

AbstractPlatformTransactionManager,我们使用的事务管理类例如 DataSourceTransactionManager等都

是这个类的子类。

一般事务定义步骤:

TransactionDefinition td = new TransactionDefinition();

TransactionStatus ts = nsaction(td);

try

{ //do sth

(ts);

}

catch(Exception e){ck(ts);}

spring提供的事务管理可以分为两类:编程式的和声明式的。编程式的,比较灵活,但是代码量大,存在

重复的代码比较多;声明式的比编程式的更灵活。

编程式主要使用transactionTemplate。省略了部分的提交,回滚,一系列的事务对象定义,需注入事务管

理对象.

void add()

{

e( new TransactionCallback(){

pulic Object doInTransaction(TransactionStatus ts)

{ //do sth}

}

}

声明式:

使用TransactionProxyFactoryBean:

class="ctionProxyFactoryBean">

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

id="userManager"

PROPAGATION_REQUIRED,readOnly

围绕Poxy的动态代理 能够自动的提交和回滚事务

ctionProxyFactoryBean

PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。

PROPAGATION_SUPPORTS--支持当前事务,如果当前没有事务,就以非事务方式执行。

PROPAGATION_MANDATORY--支持当前事务,如果当前没有事务,就抛出异常。

PROPAGATION_REQUIRES_NEW--新建事务,如果当前存在事务,把当前事务挂起。

PROPAGATION_NOT_SUPPORTED--以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

PROPAGATION_NEVER--以非事务方式执行,如果当前存在事务,则抛出异常。

PROPAGATION_NESTED--如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则进行与

PROPAGATION_REQUIRED类似的操作。

Spring 事务管理创造性的解决了很多以前要用重量级的应用服务器才能解决的事务问题,那么其实现原理

一定很深奥吧?可是如果读者仔细研究了Spring事务管理的代码以后就会发现,事务管理其实也是如此简

单的事情。这也印证了在本书开头的一句话“重剑无锋、大巧不工”,Spring并没有使用什么特殊的API,

它运行的原理就是事务的原理。下面是DataSourceTransactionManager的启动事务用的代码(经简化):

protected void doBegin(Object transaction, TransactionDefinition definition)

{

DataSourceTransactionObject txObject =

(DataSourceTransactionObject) transaction;

Connection con = null;

try

{

if (nectionHolder() == null)

{

Connection newCon = nection();

nectionHolder(

new ConnectionHolder(newCon), true);

}

nectionHolder()

.setSynchronizedWithTransaction(true);

con = nectionHolder().getConnection();

Integer previousIsolationLevel = DataSourceUtils

.prepareConnectionForTransaction(con, definition);

viousIsolationLevel(previousIsolationLevel);

if (oCommit())