iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Spring中怎么创建事务
  • 731
分享到

Spring中怎么创建事务

2023-06-14 07:06:40 731人浏览 八月长安
摘要

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

这篇文章主要介绍了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; }}
@Beanpublic 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中怎么创建事务”这篇文章对大家有帮助,同时也希望大家多多支持编程网,关注编程网精选频道,更多相关知识等着你来学习!

--结束END--

本文标题: Spring中怎么创建事务

本文链接: https://www.lsjlt.com/news/268839.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring中怎么创建事务
    这篇文章主要介绍了Spring中怎么创建事务,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。Spring事务执行原理通过创建一个BeanFactoryTransactionAt...
    99+
    2023-06-14
  • Spring事务执行流程及如何创建事务
    目录执行流程具体分析创建事务主要两部分:获取事务状态构建事务信息接上节内容,Spring事务执行原理通过创建一个BeanFactoryTransactionAttributeSour...
    99+
    2024-04-02
  • 怎么在Spring IOC中创建对象
    这篇文章将为大家详细讲解有关怎么在Spring IOC中创建对象,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。一、 使用无参构造创建对象(默认方式)创建实体类注意:属性必须要有set方法,来...
    99+
    2023-06-14
  • MySql事务处理怎么创建
    本篇内容主要讲解“MySql事务处理怎么创建”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“MySql事务处理怎么创建”吧!#本文中我的用计算机的MYSQL数据库...
    99+
    2024-04-02
  • Java Spring Cloud怎么创建服务注册中心
    本篇内容介绍了“Java Spring Cloud怎么创建服务注册中心”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!服务注册中心:我们要用到...
    99+
    2023-06-05
  • idea怎么创建spring项目
    要创建一个Spring项目,可以按照以下步骤进行:1. 确保你已经安装了Java开发环境(JDK)和Maven构建工具。如果没有安装...
    99+
    2023-09-21
    spring idea
  • Java Spring Cloud怎么创建账户服务
    本篇内容介绍了“Java Spring Cloud怎么创建账户服务”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!账户服务新建一个基本的 Sp...
    99+
    2023-06-05
  • Spring中怎么管理事务
    今天小编给大家分享一下Spring中怎么管理事务的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。什么是事务一个数据库事务是一个...
    99+
    2023-07-02
  • Spring复杂对象怎么创建
    本文小编为大家详细介绍“Spring复杂对象怎么创建”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring复杂对象怎么创建”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。什么是复杂类型,比如连接数据库的Con...
    99+
    2023-06-26
  • Spring-AOP怎么自动创建代理
    本篇内容主要讲解“Spring-AOP怎么自动创建代理”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring-AOP怎么自动创建代理”吧!实例代码已托管到Github—> https:...
    99+
    2023-06-20
  • 怎么用Thymeleaf创建Spring Boot项目
    这篇“怎么用Thymeleaf创建Spring Boot项目”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们...
    99+
    2024-04-02
  • 怎么用Spring Initializr创建Springboot项目
    本篇内容介绍了“怎么用Spring Initializr创建Springboot项目”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1.简介S...
    99+
    2023-06-27
  • Mysql数据库中怎么创建一个事件
    Mysql数据库中怎么创建一个事件,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。  事件简介  事件(event)是MySQL在相应的时刻...
    99+
    2024-04-02
  • Spring容器的创建过程中怎么注册BeanPostProcessor
    这篇文章主要介绍了Spring容器的创建过程中怎么注册BeanPostProcessor,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。注册BeanPostProcessorr...
    99+
    2023-06-15
  • SqlServer怎么创建自动收缩事务日志任务
    本篇内容主要讲解“SqlServer怎么创建自动收缩事务日志任务”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SqlServer怎么创建自动收缩事务日志任务”吧...
    99+
    2024-04-02
  • 怎么使用SQL事务管理器创建新表
    这篇文章主要讲解了“怎么使用SQL事务管理器创建新表”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用SQL事务管理器创建新表”吧!使用SQL事务管理器...
    99+
    2024-04-02
  • golang gorm的Callbacks事务回滚对象怎么创建
    这篇文章主要介绍了golang gorm的Callbacks事务回滚对象怎么创建的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇golang gorm的Callbacks事务回滚对象怎么创建文...
    99+
    2023-06-30
  • oracle事务创建的方法是什么
    在 Oracle 数据库中,可以使用以下 SQL 语句来创建事务: BEGIN -- 开始事务 INSERT INT...
    99+
    2024-04-09
    oracle
  • 手把手教你怎么创建spring项目
    创建Spring项目 通过spring.io生成初始代码,配置如下 下载好会得到一个.zip文件,解压导入IDEA就可以开始了,这是基础的项目结构 让我们打开src/main/j...
    99+
    2024-04-02
  • Spring IOC容器FactoryBean工厂Bean怎么创建
    本篇内容主要讲解“Spring IOC容器FactoryBean工厂Bean怎么创建”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring IOC容器FactoryBea...
    99+
    2023-06-30
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作