Spring AOP源碼篇四之 數據庫事務

了解了Spring AOP執行過程,再看Spring事務源碼其實非常簡單。
首先從簡單使用開始, 演示Spring事務使用過程

Xml配置:

<?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 數據庫連接池 --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"><property name="url" value="jdbc:mysql:///custom_db" /><property name="username" value="root" /><property name="password" value="123456" /><property name="driverClassName" value="com.mysql.jdbc.Driver" /></bean><!-- JdbcTemplate 對象 --><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><!-- transactionManager 對象 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="*" propagation="REQUIRED"/></tx:attributes></tx:advice><aop:config><aop:advisor advice-ref="txAdvice" pointcut="execution(* org.spring.tx.dao.*.*(..))"></aop:advisor></aop:config><bean id="userDao" class="org.spring.tx.dao.UserDaoImpl"><constructor-arg index="0" ref="jdbcTemplate"></constructor-arg></bean></beans>

實體類:

package org.spring.tx.dto;public class UserDto {private Long id;private String UserName;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUserName() {return UserName;}public void setUserName(String userName) {UserName = userName;}
}

業務Dao類:

package org.spring.tx.dao;import org.spring.tx.dto.UserDto;public interface UserDao {void insert(UserDto userDto);
}
package org.spring.tx.dao;import org.spring.tx.dto.UserDto;
import org.springframework.jdbc.core.JdbcTemplate;public class UserDaoImpl implements UserDao {//注入 JdbcTemplateprivate JdbcTemplate jdbcTemplate;public UserDaoImpl(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}@Overridepublic void insert(UserDto userDto) {//創建 sql 語句String sql = "insert into user (username)values(?)";//調用方法實現Object[] args = {userDto.getUserName()};//返回影響行數int update = jdbcTemplate.update(sql,args);System.out.println("user新增條數:" + update);//throw new RuntimeException("業務出錯了!!!");}
}

測試代碼:

package org.spring.tx;import org.spring.tx.dao.UserDao;
import org.spring.tx.dto.UserDto;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainTest {public static void main(String[] args) {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-tx.xml");applicationContext.start();UserDao userDao = applicationContext.getBean(UserDao.class);UserDto userDto = new UserDto();userDto.setUserName("zhangsan");userDao.insert(userDto);applicationContext.stop();}
}

執行結果:

==================從源碼角度簡單分析一下=====================
根據Spring AOP過程(參考:Spring AOP源碼篇二之 代理工廠ProxyFactory學習-CSDN博客??Spring AOP源碼篇三之 xml配置-CSDN博客),增強工作由Advice完成,而事務的Advice對應的是TransactionInterceptor.
public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor, Serializable {public TransactionInterceptor() {}public TransactionInterceptor(PlatformTransactionManager ptm, Properties attributes) {setTransactionManager(ptm);setTransactionAttributes(attributes);}public TransactionInterceptor(PlatformTransactionManager ptm, TransactionAttributeSource tas) {setTransactionManager(ptm);setTransactionAttributeSource(tas);}//TransactionInterceptor實現了Advice(MethodInterceptor)接口,增強工作由該方法完成//核心代碼,方法調用入口public Object invoke(final MethodInvocation invocation) throws Throwable {Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);// 父類TransactionAspectSupport中方法return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {public Object proceedWithInvocation() throws Throwable {return invocation.proceed();}});}//---------------------------------------------------------------------// Serialization support//---------------------------------------------------------------------private void writeObject(ObjectOutputStream oos) throws IOException {// Rely on default serialization, although this class itself doesn't carry state anyway...oos.defaultWriteObject();// Deserialize superclass fields.oos.writeObject(getTransactionManagerBeanName());oos.writeObject(getTransactionManager());oos.writeObject(getTransactionAttributeSource());oos.writeObject(getBeanFactory());}private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {// Rely on default serialization, although this class itself doesn't carry state anyway...ois.defaultReadObject();// Serialize all relevant superclass fields.// Superclass can't implement Serializable because it also serves as base class// for AspectJ aspects (which are not allowed to implement Serializable)!setTransactionManagerBeanName((String) ois.readObject());setTransactionManager((PlatformTransactionManager) ois.readObject());setTransactionAttributeSource((TransactionAttributeSource) ois.readObject());setBeanFactory((BeanFactory) ois.readObject());}}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/42535.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/42535.shtml
英文地址,請注明出處:http://en.pswp.cn/web/42535.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【北京迅為】《i.MX8MM嵌入式Linux開發指南》-第一篇 嵌入式Linux入門篇-第十六章 Linux 第一個程序 HelloWorld

i.MX8MM處理器采用了先進的14LPCFinFET工藝&#xff0c;提供更快的速度和更高的電源效率;四核Cortex-A53&#xff0c;單核Cortex-M4&#xff0c;多達五個內核 &#xff0c;主頻高達1.8GHz&#xff0c;2G DDR4內存、8G EMMC存儲。千兆工業級以太網、MIPI-DSI、USB HOST、WIFI/BT…

S271系列RTU在旅游景區人流監控中的應用案例

S271系列RTU在旅游景區人流監控中的應用案例 隨著全球旅游業的迅猛發展&#xff0c;旅游景區的管理者越來越關注如何利用先進的技術手段提升游客體驗、優化管理效率以及確保安全。S271系列RTU作為一款先進的無線工業物聯網設備&#xff0c;在旅游景區的人流監控中展現出了其獨…

數據結構:順序表+鏈表

數據結構&#xff1a;順序表鏈表 一。順序表&#xff1a; 首先在了解順序表和鏈表之前&#xff0c;先了解一下線性表&#xff0c;**線性表&#xff08;linear list&#xff09;**是n個具有相同特征元素的有限序列 &#xff0c;在邏輯上是線性結構&#xff0c;也就是一條連續的…

自動化升級:Conda包依賴的智能更新策略

自動化升級&#xff1a;Conda包依賴的智能更新策略 引言 在科學研究和軟件開發中&#xff0c;依賴管理是確保項目順利進行的關鍵環節。Conda作為流行的包管理器&#xff0c;提供了強大的依賴更新功能&#xff0c;幫助用戶自動化和簡化依賴項的更新過程。本文將深入探討如何在…

WPF依賴附加屬性

依賴附加屬性的定義 基本過程&#xff1a;聲明、注冊、包裝 依賴附加屬性必須在依賴對象&#xff0c;附加屬性不一定&#xff0c;關注的是被附加的對象是否是依賴對象 快捷方式&#xff1a;propa tab 關鍵字&#xff1a;RegisterAttached // 方法封裝 public static int …

Unity3d C#實現基于UGUI ScrollRect的輪播圖效果功能(含源碼)

前言 輪播功能是一種常見的頁面組件&#xff0c;用于在頁面中顯示多張圖片/素材并自動或手動進行切換&#xff0c;以提高頁面的美觀度和用戶體驗。主要的功能是&#xff1a;自動/手動切換;平滑的切換效果;導航指示器等。可惜Unity的UGUI系統里沒有現成的實現該功能&#xff0c…

第五次作業(多表聯合查詢)

新增員工表emp和部門表dept create table dept (dept1 int ,dept_name varchar(11)) charsetutf8; create table emp (sid int ,name varchar(11),age int,worktime_start date,incoming int,dept2 int) charsetutf8; insert into dept values (101,財務), (102,銷售…

Shell學習——Shell echo命令

文章目錄 echo命令 echo命令 1.顯示普通字符串: echo "It is a test"這里的雙引號完全可以省略&#xff0c;以下命令與上面實例效果一致&#xff1a; echo It is a test2.顯示轉義字符 echo "\"It is a test\""結果將是: "It is a tes…

掌握MOJO命令行:參數解析的藝術

在軟件開發中&#xff0c;命令行接口&#xff08;CLI&#xff09;是一種與程序交互的強大方式&#xff0c;它允許用戶通過終端輸入指令和參數來控制程序的行為。對于MOJO語言&#xff0c;即使它是一個假想的編程語言&#xff0c;我們也可以設想它具備解析命令行參數的能力。本文…

初識C++【命名空間】【輸入輸出】【缺省參數】【函數重載】

前言 C是一種通用的編程語言&#xff0c;被廣泛用于開發各種應用程序&#xff0c;包括系統軟件、游戲、手機應用和高性能計算等。它是C語言的擴展&#xff0c;添加了許多新特性和功能&#xff0c;并支持面向對象編程。C可以在不同的平臺上編譯和運行&#xff0c;具有高效性、可…

開放式耳機哪個品牌比較好?2024最值得推薦的火爆機型!!

在這個快節奏的時代&#xff0c;我們都在尋找那些既能讓我們享受音樂&#xff0c;又能保持對外界感知的音頻設備。開放式耳機以其獨特的設計&#xff0c;滿足了這一需求&#xff0c;它們讓你在享受音樂的同時&#xff0c;還能聽到周圍環境的聲音&#xff0c;無論是安全出行還是…

華為、H3C、銳捷、思科四大設備廠商交換機配置命令總結合輯

號主&#xff1a;老楊丨11年資深網絡工程師&#xff0c;更多網工提升干貨&#xff0c;請關注公眾號&#xff1a;網絡工程師俱樂部 下午好&#xff0c;我的網工朋友。 一直以來&#xff0c;對于華為、H3C、銳捷、思科交換機的命令配置&#xff0c;不斷的有朋友留言&#xff0c;四…

OpenSNN推文:盛夏智慧之光:七月高校新聞聚焦

隨著夏日的炎炎熱浪逐漸升溫&#xff0c;七月的校園生活也如火如荼地展開。在這個充滿活力的季節里&#xff0c;各大高校不僅迎來了學術交流的高峰&#xff0c;也在科技創新、國際合作等方面取得了顯著成就。以下是本月內幾所知名高校的重要新聞動態&#xff0c;它們不僅展現了…

數據庫 視圖

-- 刪除舊的視圖&#xff08;如果存在&#xff09; DROP VIEW IF EXISTS view_employees_active; -- 創建新的視圖 CREATE VIEW view_employees_active AS SELECT id, name FROM employees WHERE status active; 注意事項 如果視圖不滿足更新條件&#xff08;如包含JOIN、…

譜瑞科技高速傳輸接口芯片選型應用

譜瑞科技股份有限公司為一專供多種普及顯示器以及個人計算機、消費性電子產品與顯示面板所使用之高速訊號傳輸接口標準之混和信號 IC 芯片之領導供貨商。譜瑞公司成立于 2005 年為一無自有晶圓廠之半導體公司&#xff0c;并于 2011 年股票在臺灣柜臺買賣中心正式掛牌交易(股票代…

深入淺出:Scikit-Learn基礎教程

引言 Scikit-Learn&#xff08;簡稱sklearn&#xff09;是Python中一個強大的機器學習庫&#xff0c;提供了豐富的工具和模塊&#xff0c;幫助我們輕松實現數據預處理、模型訓練、評估和預測。本文將通過一個簡單的教程&#xff0c;帶您快速入門Scikit-Learn&#xff0c;掌握其…

Greenplum(三)【分布式事務和兩階段提交協議】

1、事務實現原理和 WAL&#xff08;單機&#xff09; 屬性含義數據庫系統實現Atomic&#xff08;原子性&#xff09;事務中的操作要么全部正確執行&#xff0c;要么完全不執行&#xff08;要么成功、要么失敗&#xff09;Write Ahead Logging 預寫日志&#xff0c;分布式事務&…

C語言希爾排序詳解與實例

希爾排序&#xff08;Shell Sort&#xff09;&#xff0c;是由Donald Shell在1959年提出的一種排序算法。它是插入排序的一種高效改進版&#xff0c;通過引入“增量”概念&#xff0c;將原本的線性查找轉換為分段查找&#xff0c;從而顯著提升了排序效率。本文將深入探討希爾排…

SRC漏洞挖掘技巧:修改返回包的各種姿勢

聽說大家都在要星標&#xff0c;我也要一個吧&#xff0c;可以把我的公眾號打上小星星嗎&#xff1f;~ 又雙叕周一了&#xff0c;還是老樣子&#xff0c;來篇技術向的給大家提提神吧~ 如果你對漏洞挖掘或技術向不感興趣&#xff0c;那么到這就可以了&#xff0c;不用再繼續往下…

【刪庫跑路】一次刪除pip下載的所有第三方庫方法

進入命令行&#xff0c;先list看下庫存 pip list導出所有的第三方庫至一文件列表 pip freeze >requirements.txt按照列表卸載所有庫 pip uninstall -r requirements.txt -y再list看下&#xff0c;可見庫存已清空