温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring中怎么创建事务

发布时间:2021-03-22 12:36:06 来源:亿速云 阅读:385 作者:小新 栏目:开发技术

这篇文章主要介绍了Spring中怎么创建事务,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

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

执行流程

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

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

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

  4. 回调执行下一个调用链

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

  6. 提交事务

具体分析

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

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方法执行的逻辑是:

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

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

  3. 查看方法上是否存在事务

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

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

所以如果一个方法上用了@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);
 }
}

构建事务信息

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

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

  3. 事务超时设置验证

  4. 事务PropagationBehavior属性的设置验证

  5. 构建DefaultTransactionStatus。

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

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

感谢你能够认真阅读完这篇文章,希望小编分享的“Spring中怎么创建事务”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI