他类似。看getTransaction之前我们来看一下这两类和一个接口
接口PlatformTransactionManager
抽象类public abstract class AbstractPlatformTransactionManager implements PlatformTransactionManager
类public class HibernateTransactionManager extends AbstractPlatformTransactionManager,很明显,这里有一个方法模板模式。
那我们看一下AbstractPlatformTransactionManager中得getTransaction方法:
public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
Object transaction = doGetTransaction();//抽象方法,也需要子类实现,这个方法同 样很重要
// Cache debug flag to avoid repeated checks.
boolean debugEnabled = logger.isDebugEnabled();
if (debugEnabled) {
logger.debug("Using transaction object [" + transaction + "] ");
}
if (definition == null) {
// Use defaults if no transaction definition given.
definition = new DefaultTransactionDefinition();
}
if (isExistingTransaction(transaction)) {
// Existing transaction found -> check propagation behavior to find out how to behave.
return handleExistingTransaction(definition, transaction, debugEnabled);
}
// Check definition settings for new transaction.
if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
}
// No existing transaction found -> check propagation behavior to find out how to behave.
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"Transaction propagation ''mandatory'' but no existing transaction found");
}
else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
definition.getPropagationBehavior() == TransactionDefinition.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.transactionSynchronization != SYNCHRONIZATION_NEVER);
return newTransactionStatus(definition, transaction, true, newSynchronization, debugEnabled, null);
}
else {
// Create "empty" transaction: no actual transaction, but potentially synchronization.
boolean newSynchronization = (this.transactionSynchronization == SYNCHRONIZATION_ALWAYS);
return newTransactionStatus(definition, null, false, newSynchronization, debugEnabled, null);
}
}
Spring声明式事务管理源码解读之事务开始(4)
时间:2011-03-29 javaeye 张荣华
上面的代码很多地方都有解释,所以很好理解,这段代码的关键部分在doBegin (transaction,definition)这里(这是一个抽象方法,子类必须实现这个方法,
具体依赖于抽象,这个是对方法模板模式的一个概括。),前面讲到我们假设是使用 hibernate,那么就看看HibernateTransactionManager这个类吧,doBegin里的参数1, transaction其实是HibernateTransactionObject的一个实例, |