Spring事务执行流程及如何创建事务

网友投稿 710 2023-02-04

Spring事务执行流程及如何创建事务

Spring事务执行流程及如何创建事务

接上节内容,Spring事务执行原理通过创建一个BeanFactoryTransactionAttributeSourceAdvisor,并把TransactionInterceptor注入进去,而TransactionInterceptor实现了Advice接口。而Spring Aop在Spring中会把Advisor中的Advice转换成-链,然后调用。

执行流程

获取对应事务属性,也就是获取@Transactional注解上的属性

获取TransactionManager,常用的如DataSourceTransactionManager事务管理

在目标方法执行前获取事务信息并创建事务

回调执行下一个调用链

一旦出现异常,尝试异常处理,回滚事务

提交事务

具体分析

获取对应事务属性,具体代码执行流程如下:

final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);

protected TransactionAttribute computeTransactionAttribute(Method method, Class> targetClass) {

// Don't allow no-public methods as required.

//1. allowPublicMethodsOnly()返回true,只能是公共方法

if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {

return null;

}

// Ignore CGLIB subclasses - introspect the actual user class.

Class> userClass = ClassUtils.getUserClass(targetClass);

// The method may be on an interface, but we need attributes from the target class.

// If the target class is null, the method will be unchanged.

//method代表接口中的方法、specificMethod代表实现类的方法

Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);

// If we are dealing with method with generic parameters, find the original method.

//处理泛型

specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

// First try is the method in the target class.

//查看方法中是否存在事务

TransactionAttribute txAttr = findTransactionAttribute(specificMethod);

if (txAttr != null) {

return txAttr;

}

// Second try is the transaction attribute on the target class.

//查看方法所在类是否存在事务声明

txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());

if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {

return txAttr;

}

//如果存在接口,则在接口中查找

if (specificMethod != method) {

// Fallback is to look at the original method.

//查找接口方法

txAttr = findTransactionAttribute(method);

if (txAttr != null) {

return txAttr;

}

// Last fallback is the class of the original method.

//到接口类中寻找

txAttr = findTransactionAttribute(method.getDeclaringClass());

if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {

return txAttr;

}

}

return null;

}

getTransactionAttributeSource()获得的对象是在ProxyTransactionManagementConfiguration创建bean时注入的AnnotationTransactionAttributeSource对象。 AnnotationTransactionAttributeSource中getTransactionAttributeSource方法主要逻辑交给了computeTransactionAttribute方法,所以我们直接看computeTransactionAttribute代码实现。

computeTransactionAttribute方法执行的逻辑是:

判断是不是只运行公共方法,在AnnotationTransactionAttributeSource构造方法中传入true。若方法不是公共方法,则返回null。

得到具体的方法,method方法可能是接口方法或者泛型方法。

查看方法上是否存在事务

查看方法所在类上是否存在事务

查看接口的方法是否存在事务,查看接口上是否存在事务。

所以如果一个方法上用了@Transactional,类上和接口上也用了,以方法上的为主,其次才是类,最后才到接口。

获取TransactionManager,具体代码执行流程如下:

protected PlatformTransactionManager determineTransactionManager(TransactionAttribute txAttr) {

// Do not attempt to lookup tx manager if no tx attributes are set

if (txAttr == null || this.beanFactory == null) {

return getTransactionManager();

}

String qualifier = txAttr.getQualifier();

if (StringUtils.hasText(qualifier)) {

return determineQualifiedTransactionManager(qualifier);

}

else if (StringUtils.hasText(this.transactionManagerBeanName)) {

return determineQualifiedTransactionManager(this.transactionManagerBeanName);

}

else {

//常用的会走到这里

PlatformTransactionManager defaultTransactionManager = getTransactionManager();

if (defaultTransactionManager == null) {

defaultTransactionManager = this.transactionManagerCache.get(DEFAULT_TRANSACTION_MANAGER_KEY);

if (defaultTransactionManager == null) {

//从beanFactory获取PlatformTransactionManager类型的bean

defaultTransactionManager = this.beanFactory.getBean(PlatformTransactionManager.class);

this.transactionManagerCache.putIfAbsent(

DEFAULT_TRANSACTION_MANAGER_KEY, defaultTransactionManager);

}

}

return defaultTransactionManager;

}

}

@Bean

public PlatformTransactionManager txManager() {

return new DataSourceTransactionManager(dataSource());

}

创建事务主要两部分:

获取事务状态

构建事务信息

获取事务状态

代码如下:

@Override

public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {

//1.获取事务

Object transaction = doGetTransaction();

// Cache debug flag to avoid repeated checks.

boolean debugEnabled = logger.isDebugEnabled();

if (definition == null) {

// Use defaults if no transaction definition given.

definition = new DefaultTransactionDefinition();

}

//判断当前线程是否存在事务,判断依据为当前线程记录连接不为空且连接中的(connectionHolder)中的transactionActive属性不为空

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 proceed.

//如果当前线程不存在事务,但是@Transactional却声明事务为PROPAGATION_MANDATORY抛出异常

if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {

throw new IllegalTransactionStateException(

"No existing transaction found for transaction marked with propagation 'mandatory'");

}

//如果当前线程不存在事务,PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW、PROPAGATION_NESTED都得创建事务

else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||

definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||

definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {

//空挂起

SuspendedResourcesHolder suspendedResources = suspend(null);

if (debugEnabled) {

logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);

}

try {

//默认返回true

boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);

//构建事务状态

DefaultTransactionStatus status = newTransactionStatus(

definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);

//构造transaction、包括设置connectionHolder、隔离级别、timeout

//如果是新事务,绑定到当前线程

doBegin(transaction, definition);

//新事务同步设置,针对当前线程

prepareSynchronization(status, definition);

return status;

}

catch (RuntimeException ex) {

resume(null, suspendedResources);

throw ex;

}

catch (Error err) {

resume(null, suspendedResources);

throw err;

}

}

else {

// Create "empty" transaction: no actual transaction, but potentially synchronization.

if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {

logger.warn("Custom isolation level specified but no actual transaction initiated; " +

"isolation level will effectively be ignored: " + definition);

}

//声明事务是PROPAGATION_SUPPORTS

boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);

return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);

}

}

构建事务信息

获取事务,创建对应的事务实例,这里使用的是DataSourceTransactionManager中的doGetTransaction方法,创建基于JDBC的事务实例,如果当前线程中存在关于dataSoruce的连接,那么直接使用。这里有一个对保存点的设置,是否开启允许保存点取决于是否设置了允许嵌入式事务。DataSourceTransactionManager默认是开启的。

如果当先线程存在事务,则转向嵌套的事务处理。是否存在事务在DataSourceTransactionManager的isExistingTransaction方法中

事务超时设置验证

事务PropagationBehavior属性的设置验证

构建DefaultTransactionStatus。

完善transaction,包括设置connectionHolder、隔离级别、timeout,如果是新事务,绑定到当前线程

将事务信息记录在当前线程中

以上就是Spring事务执行流程及如何创建事务的详细内容,更多关于Spring事务执行流程及如何创建的资料请关注我们其它相关文章!

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:信息安全前端(信息安全前端有哪些)
下一篇:电脑打开小程序(怎么用电脑打开小程序)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~