Spring声明式事务管理源码解读之事务开始
时间:2011-03-29 javaeye 张荣华
这个是我昨天在解决问题是看源码得一点体验,可能说得比较大概,希望大家多多讨 论,把本贴得质量提高上去,因为spring实现的事务管理这部分我相信还是有点复杂的。 一个人未必能想得十分清楚
在spring的声明式事务管理中,它是如何判定一个及标记一个方法是否应该是处在事 务体之中呢。
首先要理解的是spring是如何来标记一个方法是否应该处在事务体之中的。有这样一 个接口TransactionDefinition,其中定义了很多常量,它还有一个子接口 TransactionAttribute,其中只有一个方法rollback。
TransactionDefinition中有很多常量定义,它们分别属于两种类型,传播途径和隔离 级别
代码
/*** Support a current transaction, create a new one if none
exists.* Analogous to EJB transaction attribute of the same name.*
<p>This is typically the default setting of a transaction
definition.*/int PROPAGATION_REQUIRED = 0;
当然其中也定义了隔离级别
/**
* A constant indicating that dirty reads are prevented; non-repeatable reads
* and phantom reads can occur. This level only prohibits a transaction
* from reading a row with uncommitted changes in it.
* @see java.sql.Connection#TRANSACTION_READ_COMMITTED
*/
int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED;
同时还有两个对应的方法来得到这样的传播途径和隔离级别
/**
* Return the propagation behavior.
* Must return one of the PROPAGATION constants.
* @see #PROPAGATION_REQUIRED
* @see org.springframework.transaction.support.TransactionSynchronizationManager#isAc tualTransactionActive()
*/
int getPropagationBehavior();
/**
* Return the isolation level.
* Must return one of the ISOLATION constants.
* <p>Only makes sense in combination with PROPAGATION_REQUIRED or
* PROPAGATION_REQUIRES_NEW.
* <p>Note that a transaction manager that does not support custom
* isolation levels will throw an exception when given any other level
* than ISOLATION_DEFAULT.
* @see #ISOLATION_DEFAULT
*/
int getIsolationLevel();
这个接口有一个默认的实现DefaultTransactionDefinition。然后它还有子类,比如 说
DefaultTransactionAttribute。Spring在判断一个方法是否需要事务体的时候其实是 创建一个TransactionAttribute实现的实例.
Spring声明式事务管理源码解读之事务开始(2)
时间:2011-03-29 javaeye 张荣华
有了上面的简单介绍就可以进入真正判断是否需要事务的地方了。这个方法在 TransactionAspectSupport类里,
/**
* Create a transaction if necessary.
* @param method method about to execute
* @param targetClass class the method is on
* @return a TransactionInfo object, whether or not a transaction was created.
* The hasTransaction() method on TransactionInfo can be used to tell if there
* was a transaction created.
*/
protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) {
// If the transaction attribute is null, the method is non-transactional.
final TransactionAttribute sourceAttr =
this.transactionAttributeSource.getTransactionAttribute(method, targetClass);//就是在这里判断了这个方法的事务属性
TransactionAttribute txAttr = sourceAttr;
//
|