<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
/* 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;
不用Springboot依賴,引入mysql驅動依賴、spring-beans、spring-jdbc、Spring-context依賴
<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 依賴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>
首先在resources目錄下建立一個spring.xml檔案,Spring框架為了宣告自己的Xml規範,在<beans>標籤裡定義了spring 框架指定模組的協定設定, 我們可以通過Index of /schema存取spring框架的所有模組包,各模組包含了不同版本的xsd檔案。
點選進入context目錄,檢視xsd檔案:
比如我要通過xml的形式設定一個bean, 需要在beans標籤中宣告 xmln的值為:
http://www.springframework.org/schema/beans
如果我想用spring的context模組,那麼需要宣告
xmlns:context="http://www.springframework.org/schema/context"
同時在xsi: schemeLocation裡新增context的url和spring-contxt.xsd的url:
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
例如我建立一個能在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>
如果沒有在beans標籤裡宣告協定,那麼在設定bean時會出現找不到指定標籤的問題。
在spring.xml檔案中新增設定事務設定,使用 annotation-driven 屬性開啟事務啟動,
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" mode="proxy"/>
proxy-target-class預設為false, mode預設模式為proxy,可不用設定,待會從原始碼角度分析不同模式的事務開啟。
接著設定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屬性設定:
因此我們需要接著設定資料來源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設定一個bean, 參照dataSource資料來源。
<!-- 設定bean,指定資料來源--> <bean id="userService" class="service.UserService"> <property name="dataSource" ref="ds"/> </bean>
通過dataSouce bean注入JDBCTemplate, 新增一個update(int id,String name)方法, 類上新增@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!"); } }
使用ClassPathXmlApplicationContext類載入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); } }
資料庫一條記錄:
update方法裡放開//throw new RuntimeException("error!"); 註釋,執行後
資料庫裡的記錄沒有修改,@Tranasctional註解生效。
重新執行後,觀察結果
資料庫也更新過來了。
前面的篇幅從xml的設定形式解釋了Transaction整合過程,為什麼要從xml形式入手transaction, 是為了後面閱讀Spring-tx原始碼做準備。
根據spring.xml檔案裡設定的tx:annitation-driven 關鍵字在Spring框架裡全域性搜尋,找到目標類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()); // 註冊事務 registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser()); registerBeanDefinitionParser("jta-transaction-manager", new JtaTransactionManagerBeanDefinitionParser()); } }
找到了annotation-driven, 這個地方建立了一個AnnotationDrivenBeanDefinitionParser範例。
AnnotationDrivenBeanDefinitionParser 類的作用是解析spring.xml裡的設定<tx:annotation-driven>標籤,並根據設定的mode選擇不同的模式取建立Transaction的整個初始化流程,此處也就是整個架Transaction架構的開始地方。
Spring事務註冊的模式為動態代理模式,具體實現有2種: aspectj和proxy,可通過設定來選擇使用那種形式的事務註冊, 如果不設定mode那麼使用預設的proxy形式建立,如果我們要使用aspectj模式開啟事務,那麼就設定mode="aspectj"。
<tx:annotation-driven transaction-manager="transactionManager" mode="aspectj">
我們可以看到Spring事務的開啟是預設是以AOP為基礎的。
AopAutoProxyConfigurer 的configureAutoProxyCreator方法註冊了3個Bean, 該3個Bean 是驅動Spring 事務架構的核心支柱,分別是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")); } // 事務通知器 transaction advisor, 基於AOP實現的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事務的目標方法的增強,通過代理完成Spring 事務的提交、例外處理和回滾。
TransactionInterceptor是Spring 事務對目標方法的增強器,說簡單點就是一層代理,基於Aop實現,實現了spring-aop的Advice介面,同時實現了IntializingBean和BeanFactoryAware介面,只要有事務的執行,那麼目標方法的呼叫類在invoke()方法會生成一個代理物件,通過invoke()方法對目標呼叫方法進行增強。
@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()實現:
@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); }
Spring 建立事務的方式有二種: 宣告式事務和程式設計式事務, 我們可以通過分析一種理解核心流程和原理即可。
進入invokeWithinTransaction()方法直接看宣告式事務執行過程的原始碼:
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) { // Standard transaction demarcation with getTransaction and commit/rollback calls. // 建立事務 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 // 根據指定異常進行回滾。 completeTransactionAfterThrowing(txInfo, ex); throw ex; } finally { cleanupTransactionInfo(txInfo); } // 提交事務 commitTransactionAfterReturning(txInfo); return retVal; }
invokeWithinTransaction方法做了哪些事?
1)通過createTransactionIfNecessary方法建立一個事務,相當於此處開啟一個事務。
2)invocation.proceedWithInvocation() 執行目標方法呼叫。
3) 如果出現異常,那麼completeTransactionAfterThrowing處理異常。
4) 在finally 清除掉transaction相關的資訊,同時在commitTransactionAfterReturning 提交事務。
我們可以從上面的原始碼中發現通過transactionManager執行回滾操作。
txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
到此這篇關於Spring Transaction事務實現流程原始碼解析的文章就介紹到這了,更多相關Spring Transaction內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45