Spring Transaction事務(wù)實(shí)現(xiàn)流程源碼解析
一、基于xml形式開(kāi)啟Transaction
1. 創(chuàng)建數(shù)據(jù)庫(kù)user
/* Navicat Premium Data Transfer Source Server : win-local Source Server Type : MySQL Source Server Version : 50737 Source Host : localhost:3306 Source Schema : db0 Target Server Type : MySQL Target Server Version : 50737 File Encoding : 65001 Date: 24/04/2022 20:27:41 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `age` int(11) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
2. 創(chuàng)建一個(gè)maven 項(xiàng)目
不用Springboot依賴(lài),引入mysql驅(qū)動(dòng)依賴(lài)、spring-beans、spring-jdbc、Spring-context依賴(lài)
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.18</version> </dependency> <!-- spring jdbc 依賴(lài)spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.18</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.18</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> </dependencies>
3. 通過(guò)xml形式配置事務(wù)
1) 創(chuàng)建Spring命名空間
首先在resources目錄下創(chuàng)建一個(gè)spring.xml文件,Spring框架為了聲明自己的Xml規(guī)范,在<beans>標(biāo)簽里定義了spring 框架指定模塊的協(xié)議配置, 我們可以通過(guò)Index of /schema訪(fǎng)問(wèn)spring框架的所有模塊包,各模塊包含了不同版本的xsd文件。
點(diǎn)擊進(jìn)入context目錄,查看xsd文件:
比如我要通過(guò)xml的形式配置一個(gè)bean, 需要在beans標(biāo)簽中聲明 xmln的值為:
http://www.springframework.org/schema/beans
如果我想用spring的context模塊,那么需要聲明
xmlns:context="http://www.springframework.org/schema/context"
同時(shí)在xsi: schemeLocation里添加context的url和spring-contxt.xsd的url:
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
例如我創(chuàng)建一個(gè)能在xml中使用spring-beans模塊,spring-txt模塊,spring-context模塊的配置如下:
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd "> </beans>
如果沒(méi)有在beans標(biāo)簽里聲明協(xié)議,那么在配置bean時(shí)會(huì)出現(xiàn)找不到指定標(biāo)簽的問(wèn)題。
2) 開(kāi)啟事務(wù)配置
在spring.xml文件中添加配置事務(wù)配置,使用 annotation-driven 屬性開(kāi)啟事務(wù)啟動(dòng),
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" mode="proxy"/>
proxy-target-class默認(rèn)為false, mode默認(rèn)模式為proxy,可不用配置,待會(huì)從源碼角度分析不同模式的事務(wù)開(kāi)啟。
接著配置transactionManager, 指定class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" mode="proxy"/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="ds"/> </bean>
DataSourceTransactionManager里包含了DataSource屬性配置:
因此我們需要接著配置數(shù)據(jù)源bean 別名為
<bean id="ds" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="username" value="root"/> <property name="password" value="root"/> <property name="url" value="jdbc:mysql://localhost:3306/db0?useSSL=false"/> <property name="initialSize" value="5"/> <property name="maxIdle" value="2"/> <property name="maxTotal" value="100"/> </bean>
接著給Service配置一個(gè)bean, 引用dataSource數(shù)據(jù)源。
<!-- 配置bean,指定數(shù)據(jù)源--> <bean id="userService" class="service.UserService"> <property name="dataSource" ref="ds"/> </bean>
3) 創(chuàng)建UserService類(lèi)
通過(guò)dataSouce bean注入JDBCTemplate, 添加一個(gè)update(int id,String name)方法, 類(lèi)上添加@Transactional(propagation = Propagation.REQUIRED)。
package service; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.sql.DataSource; @Transactional(propagation = Propagation.REQUIRED) public class UserService { private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public String getUserName(int id) { return jdbcTemplate.query("select * from db0.user where id= ?", rs -> rs.next() ? rs.getString(2) : "", new Object[]{id}); } public void updateUser(int id, String name) { jdbcTemplate.update(" update user set name =? where id= ?", new Object[]{name, id}); // throw new RuntimeException("error!"); } }
4. 測(cè)試事務(wù)
使用ClassPathXmlApplicationContext類(lèi)加載spring.xml文件
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import service.UserService; public class UserServiceTests { @Test public void testTransaction() { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); UserService userService = context.getBean("userService", UserService.class); String name = userService.getUserName(1); System.out.println("名字:"+name); userService.updateUser(1, "bing"); String updateName = userService.getUserName(1); System.out.println("更新后的名字:" + updateName); } }
數(shù)據(jù)庫(kù)一條記錄:
1) 拋出RuntimeException
update方法里放開(kāi)//throw new RuntimeException("error!"); 注釋?zhuān)瑘?zhí)行后
數(shù)據(jù)庫(kù)里的記錄沒(méi)有修改,@Tranasctional注解生效。
2) 注釋掉RuntimeException
重新執(zhí)行后,觀察結(jié)果
數(shù)據(jù)庫(kù)也更新過(guò)來(lái)了。
前面的篇幅從xml的配置形式解釋了Transaction集成過(guò)程,為什么要從xml形式入手transaction, 是為了后面閱讀Spring-tx源碼做準(zhǔn)備。
二、事務(wù)開(kāi)啟入口TxNamespaceHandler
根據(jù)spring.xml文件里配置的tx:annitation-driven 關(guān)鍵字在Spring框架里全局搜索,找到目標(biāo)類(lèi)TxNamespaceHandler。位于spring-tx模塊中的 org.springframework.transaction.config包下。
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.config; import org.w3c.dom.Element; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * {@code NamespaceHandler} allowing for the configuration of * declarative transaction management using either XML or using annotations. * * <p>This namespace handler is the central piece of functionality in the * Spring transaction management facilities and offers two approaches * to declaratively manage transactions. * * <p>One approach uses transaction semantics defined in XML using the * {@code <tx:advice>} elements, the other uses annotations * in combination with the {@code <tx:annotation-driven>} element. * Both approached are detailed to great extent in the Spring reference manual. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 */ public class TxNamespaceHandler extends NamespaceHandlerSupport { static final String TRANSACTION_MANAGER_ATTRIBUTE = "transaction-manager"; static final String DEFAULT_TRANSACTION_MANAGER_BEAN_NAME = "transactionManager"; static String getTransactionManagerName(Element element) { return (element.hasAttribute(TRANSACTION_MANAGER_ATTRIBUTE) ? element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE) : DEFAULT_TRANSACTION_MANAGER_BEAN_NAME); } @Override public void init() { registerBeanDefinitionParser("advice", new TxAdviceBeanDefinitionParser()); // 注冊(cè)事務(wù) registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser()); registerBeanDefinitionParser("jta-transaction-manager", new JtaTransactionManagerBeanDefinitionParser()); } }
找到了annotation-driven, 這個(gè)地方創(chuàng)建了一個(gè)AnnotationDrivenBeanDefinitionParser實(shí)例。
AnnotationDrivenBeanDefinitionParser
AnnotationDrivenBeanDefinitionParser 類(lèi)的作用是解析spring.xml里的配置<tx:annotation-driven>標(biāo)簽,并根據(jù)配置的mode選擇不同的模式取創(chuàng)建Transaction的整個(gè)初始化流程,此處也就是整個(gè)架Transaction架構(gòu)的開(kāi)始地方。
Spring事務(wù)注冊(cè)的模式為動(dòng)態(tài)代理模式,具體實(shí)現(xiàn)有2種: aspectj和proxy,可通過(guò)配置來(lái)選擇使用那種形式的事務(wù)注冊(cè), 如果不配置mode那么使用默認(rèn)的proxy形式創(chuàng)建,如果我們要使用aspectj模式開(kāi)啟事務(wù),那么就配置mode="aspectj"。
<tx:annotation-driven transaction-manager="transactionManager" mode="aspectj">
我們可以看到Spring事務(wù)的開(kāi)啟是默認(rèn)是以AOP為基礎(chǔ)的。
三、AOP驅(qū)動(dòng)事務(wù)
AopAutoProxyConfigurer 的configureAutoProxyCreator方法注冊(cè)了3個(gè)Bean, 該3個(gè)Bean 是驅(qū)動(dòng)Spring 事務(wù)架構(gòu)的核心支柱,分別是TransactionAttributeSource、TransactionInterceptor、TransactionAttributeSourceAdvisor。
private static class AopAutoProxyConfigurer { public static void configureAutoProxyCreator(Element element, ParserContext parserContext) { AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element); String txAdvisorBeanName = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME; if (!parserContext.getRegistry().containsBeanDefinition(txAdvisorBeanName)) { Object eleSource = parserContext.extractSource(element); // Create the TransactionAttributeSource definition. RootBeanDefinition sourceDef = new RootBeanDefinition( "org.springframework.transaction.annotation.AnnotationTransactionAttributeSource"); sourceDef.setSource(eleSource); sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef); // Create the TransactionInterceptor definition. RootBeanDefinition interceptorDef = new RootBeanDefinition(TransactionInterceptor.class); interceptorDef.setSource(eleSource); interceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registerTransactionManager(element, interceptorDef); interceptorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName)); String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef); // Create the TransactionAttributeSourceAdvisor definition. RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryTransactionAttributeSourceAdvisor.class); advisorDef.setSource(eleSource); advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); advisorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName)); advisorDef.getPropertyValues().add("adviceBeanName", interceptorName); if (element.hasAttribute("order")) { advisorDef.getPropertyValues().add("order", element.getAttribute("order")); } // 事務(wù)通知器 transaction advisor, 基于AOP實(shí)現(xiàn)的advisor parserContext.getRegistry().registerBeanDefinition(txAdvisorBeanName, advisorDef); CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource); compositeDef.addNestedComponent(new BeanComponentDefinition(sourceDef, sourceName)); compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName)); compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, txAdvisorBeanName)); parserContext.registerComponent(compositeDef); } } }
其中TransactionInterceptor是Spring事務(wù)的目標(biāo)方法的增強(qiáng),通過(guò)代理完成Spring 事務(wù)的提交、異常處理和回滾。
TransactionInterceptor
TransactionInterceptor是Spring 事務(wù)對(duì)目標(biāo)方法的增強(qiáng)器,說(shuō)簡(jiǎn)單點(diǎn)就是一層代理,基于Aop實(shí)現(xiàn),實(shí)現(xiàn)了spring-aop的Advice接口,同時(shí)實(shí)現(xiàn)了IntializingBean和BeanFactoryAware接口,只要有事務(wù)的執(zhí)行,那么目標(biāo)方法的調(diào)用類(lèi)在invoke()方法會(huì)生成一個(gè)代理對(duì)象,通過(guò)invoke()方法對(duì)目標(biāo)調(diào)用方法進(jìn)行增強(qiáng)。
@FunctionalInterface public interface MethodInterceptor extends Interceptor { /** * Implement this method to perform extra treatments before and * after the invocation. Polite implementations would certainly * like to invoke {@link Joinpoint#proceed()}. * @param invocation the method invocation joinpoint * @return the result of the call to {@link Joinpoint#proceed()}; * might be intercepted by the interceptor * @throws Throwable if the interceptors or the target object * throws an exception */ Object invoke(MethodInvocation invocation) throws Throwable; }
TransactionInterceptor的invoke()實(shí)現(xiàn):
@Override @Nullable public Object invoke(final MethodInvocation invocation) throws Throwable { // Work out the target class: may be {@code null}. // The TransactionAttributeSource should be passed the target class // as well as the method, which may be from an interface. Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null); // Adapt to TransactionAspectSupport's invokeWithinTransaction... return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed); }
創(chuàng)建事務(wù)
Spring 創(chuàng)建事務(wù)的方式有二種: 聲明式事務(wù)和編程式事務(wù), 我們可以通過(guò)分析一種理解核心流程和原理即可。
進(jìn)入invokeWithinTransaction()方法直接看聲明式事務(wù)執(zhí)行過(guò)程的源代碼:
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) { // Standard transaction demarcation with getTransaction and commit/rollback calls. // 創(chuàng)建事務(wù) TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification); Object retVal = null; try { // This is an around advice: Invoke the next interceptor in the chain. // This will normally result in a target object being invoked. retVal = invocation.proceedWithInvocation(); } catch (Throwable ex) { // target invocation exception // 根據(jù)指定異常進(jìn)行回滾。 completeTransactionAfterThrowing(txInfo, ex); throw ex; } finally { cleanupTransactionInfo(txInfo); } // 提交事務(wù) commitTransactionAfterReturning(txInfo); return retVal; }
invokeWithinTransaction方法做了哪些事?
1)通過(guò)createTransactionIfNecessary方法創(chuàng)建一個(gè)事務(wù),相當(dāng)于此處開(kāi)啟一個(gè)事務(wù)。
2)invocation.proceedWithInvocation() 執(zhí)行目標(biāo)方法調(diào)用。
3) 如果出現(xiàn)異常,那么completeTransactionAfterThrowing處理異常。
4) 在finally 清除掉transaction相關(guān)的信息,同時(shí)在commitTransactionAfterReturning 提交事務(wù)。
回滾事務(wù)
我們可以從上面的源碼中發(fā)現(xiàn)通過(guò)transactionManager執(zhí)行回滾操作。
txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
到此這篇關(guān)于Spring Transaction事務(wù)實(shí)現(xiàn)流程源碼解析的文章就介紹到這了,更多相關(guān)Spring Transaction內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 淺談Spring中@Transactional事務(wù)回滾及示例(附源碼)
- Spring事務(wù)@Transactional注解四種不生效案例場(chǎng)景分析
- springboot編程式事務(wù)TransactionTemplate的使用說(shuō)明
- Spring中的@Transactional的工作原理
- spring聲明式事務(wù)@Transactional底層工作原理
- spring中12種@Transactional的失效場(chǎng)景(小結(jié))
- Spring事務(wù)處理Transactional,鎖同步和并發(fā)線(xiàn)程
- 基于Spring中的事務(wù)@Transactional細(xì)節(jié)與易錯(cuò)點(diǎn)、幻讀
- spring聲明式事務(wù) @Transactional 不回滾的多種情況以及解決方案
相關(guān)文章
淺談ArrayList和LinkedList到底誰(shuí)更快
今天給大家?guī)?lái)的是關(guān)于Java的相關(guān)知識(shí),文章圍繞著ArrayList和LinkedList到底誰(shuí)更快展開(kāi),文中有非常詳細(xì)的介紹,需要的朋友可以參考下2021-06-06Java 日期格式加上指定月數(shù)(一個(gè)期限)得到一個(gè)新日期的實(shí)現(xiàn)代碼
這篇文章主要介紹了Java 日期格式加上指定月數(shù)(一個(gè)期限)得到一個(gè)新日期的實(shí)現(xiàn)代碼,需要的朋友可以參考下2018-05-05詳解使用Spring AOP和自定義注解進(jìn)行參數(shù)檢查
本篇文章主要介紹了詳解使用Spring AOP和自定義注解進(jìn)行參數(shù)檢查,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Springboot整合SpringSecurity的完整案例詳解
Spring Security是基于Spring生態(tài)圈的,用于提供安全訪(fǎng)問(wèn)控制解決方案的框架,Spring Security登錄認(rèn)證主要涉及兩個(gè)重要的接口 UserDetailService和UserDetails接口,本文對(duì)Springboot整合SpringSecurity過(guò)程給大家介紹的非常詳細(xì),需要的朋友參考下吧2024-01-01Java實(shí)現(xiàn)橋接方法isBridge()和合成方法isSynthetic()
本文主要介紹了Java實(shí)現(xiàn)橋接方法isBridge()和合成方法isSynthetic(),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06java實(shí)現(xiàn)多文件上傳至本地服務(wù)器功能
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)多文件上傳至本地服務(wù)器功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01Springboot獲取jar包中resources資源目錄下的文件
今天在項(xiàng)目中遇到一個(gè)業(yè)務(wù)場(chǎng)景,需要用到resources資源目錄下的文件,本文主要介紹了Springboot獲取jar包中resources資源目錄下的文件,感興趣的可以了解一下2023-12-12Springboot整合GateWay+Nacos實(shí)現(xiàn)動(dòng)態(tài)路由
本文主要介紹了Springboot整合GateWay+Nacos實(shí)現(xiàn)動(dòng)態(tài)路由,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08