当前位置: 首页 > news >正文

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());}}

相关文章:

Spring AOP源码篇四之 数据库事务

了解了Spring AOP执行过程&#xff0c;再看Spring事务源码其实非常简单。 首先从简单使用开始, 演示Spring事务使用过程 Xml配置&#xff1a; <?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www.springframework.org/schema…...

小波与傅里叶变换的对比(Python)

直接上代码&#xff0c;理论可以去知乎看。 #Import necessary libraries %matplotlib inline import numpy as np import matplotlib.pyplot as plt import seaborn as snsimport pywt from scipy.ndimage import gaussian_filter1d from scipy.signal import chirp import m…...

Linux-sqlplus安装

1.下载安装包 下载入口&#xff1a;安装包 下载对应版本&#xff1a; oracle-instantclient-sqlplus-21.14.0.0.0-1.x86_64.rpm oracle-instantclient-basic-21.14.0.0.0-1.x86_64.rpm oracle-instantclient-devel-21.14.0.0.0-1.x86_64.rpm 2.安装 [rootpromethues-01 tmp…...

LeetCode 算法:课程表 c++

原题链接&#x1f517;&#xff1a;课程表 难度&#xff1a;中等⭐️⭐️ 题目 你这个学期必须选修 numCourses 门课程&#xff0c;记为 0 到 numCourses - 1 。 在选修某些课程之前需要一些先修课程。 先修课程按数组 prerequisites 给出&#xff0c;其中 prerequisites[i]…...

前端面试题30(闭包和作用域链的关系)

闭包和作用域链在JavaScript中是紧密相关的两个概念&#xff0c;理解它们之间的关系对于深入掌握JavaScript的执行机制至关重要。 作用域链 作用域链是一个链接列表&#xff0c;它包含了当前执行上下文的所有父级执行上下文的变量对象。每当函数被调用时&#xff0c;JavaScri…...

A股本周在3000点以下继续筑底,本周依然继续探底?

夜已深&#xff0c;市场传来了3个浓烈的消息&#xff0c;炸锅了&#xff0c;恐有大事发生&#xff0c;马上告诉所有人&#xff1a; 消息面&#xff1a; 1、中国经济周刊首席评论员钮文新称&#xff1a;不要等中小投资者都彻底希望&#xff0c;销户离场了&#xff0c;才发现该…...

Javadoc介绍

Javadoc 是用于生成 Java 代码文档的工具。它利用特定的注释格式,将 Java 源代码中的注释提取出来,并生成 HTML 文档。Javadoc 注释通常位于类、接口、构造函数、方法和字段的声明之前,以 /** 开始,以 */ 结束。以下是 Javadoc 注释的一些主要元素和使用方法: 基本语法 …...

C# Application.DoEvents()的作用

文章目录 1、详解 Application.DoEvents()2、示例处理用户事件响应系统事件控制台输出游戏和多媒体应用与操作系统的交互 3、注意事项总结 Application.DoEvents() 是 .NET 框架中的一个方法&#xff0c;它主要用于处理消息队列中的事件。在 Windows 应用程序中&#xff0c;当一…...

IDEA如何创建原生maven子模块

文件 -> 新建 -> 新模块 -> Maven ArcheTypeMaven ArcheType界面中的输入框介绍 名称&#xff1a;子模块的名称位置&#xff1a;子模块存放的路径名创建Git仓库&#xff1a;子模块不单独作为一个git仓库&#xff0c;无需勾选JDK&#xff1a;JDK版本号父项&#xff1a;…...

LCD EMC 辐射 测试随想

最近做几个产品过认证。 有带2.8寸 MCU8080接口的小屏&#xff08;320 X 240&#xff09;&#xff0c;也有RGB接口的10.1寸的大屏(800*600). 以下为个人随想&#xff0c;不知道是否正确&#xff0c;仅作记录。 测试发现辐射的核心问题还是在于时钟及其倍频所产生的尖峰。 记得读…...

Docker安装遇到问题:curl: (7) Failed to connect to download.docker.com port 443: 拒绝连接

问题描述 首先&#xff0c;完全按照Docker官方文档进行安装&#xff1a; Install Docker Engine on Ubuntu | Docker Docs 在第1步&#xff1a;Set up Dockers apt repository&#xff0c;执行如下指令&#xff1a; sudo curl -fsSL https://download.docker.com/linux/ubu…...

阿里云安装rabbitMQ

1、首先看linux 版本 uname -a如果时centos 7 可以参考其他文档。我这里是centos 8 这个很重要 。网上全是按centos7 按照。导致我前面一直安装不上 各种问题。 2、查看rabbitmq 对应 erl 的版本下载 https://www.rabbitmq.com/docs/which-erlang 选择rabbitmq 3.11.19 选择…...

中文大模型基准测评2024上半年报告

中文大模型基准测评2024上半年报告 原创 SuperCLUE CLUE中文语言理解测评基准 2024年07月09日 18:09 浙江 SuperCLUE团队 2024/07 背景 自2023年以来&#xff0c;AI大模型在全球范围内掀起了有史以来规模最大的人工智能浪潮。进入2024年&#xff0c;全球大模型竞争态势日益加…...

新火种AI|OpenAI的CEO又有新动作?这次他成立了AI健康公司

作者&#xff1a;一号 编辑&#xff1a;美美 AI技术即将改变医疗健康市场。 就在前两天&#xff0c;人工智能和医疗健康领域迎来了一个重要时刻。OpenAI的CEO萨姆阿尔特曼&#xff08;Sam Altman&#xff09;与Thrive Global的CEO阿里安娜赫芬顿&#xff08;Arianna Huffing…...

中介子方程五十

XXFXXaXnXaXXαXLXyXXWXuXeXKXXiXyXΣXXΣXXVXuXhXXWXηXXiXhXXpXXhXiXXηXWXXhXuXVXXΣXXΣXyXiXXKXeXuXWXXyXLXαXXaXnXaXXFXXaXnXaXXαXLXyXXWXuXeXKXXiXyXΣXXΣXXVXuXhXXWXηXXiXhXXpXXhXiXXηXWXXhXuXVXXΣXXΣXyXiXXKXeXuXWXXyXLXαXXaXnXaXXFXXuXXWXXuXXdXXrXXαXXuXpX…...

如何借助社交媒体影响者的力量,让品牌影响力倍增?

一、引言&#xff1a;为何社交媒体影响者如此关键&#xff1f; 在信息爆炸的今天&#xff0c;社交媒体已成为塑造消费者行为与品牌认知的重要渠道。社交媒体影响者&#xff0c;凭借其在特定领域的专业知识、庞大的粉丝基础及高度的互动性&#xff0c;成为了品牌传播不可忽视的…...

Python面试题:Python 中的 `property` 函数有什么用?

在 Python 中&#xff0c;property 函数用于创建和管理类中的属性。它允许你将方法转换为属性&#xff0c;这样你可以像访问变量一样访问这些方法。这对于控制属性的访问和修改非常有用&#xff0c;因为它允许你在属性访问时执行额外的逻辑&#xff08;如验证或计算&#xff09…...

十五、小型电脑没有数字键及insert,怎么解决IDEA快速插入getset构造这些方法

&#x1f33b;&#x1f33b;目录 一、小型电脑没有数字键及insert&#xff0c;怎么解决IDEA快速插入getset构造这些方法 一、小型电脑没有数字键及insert&#xff0c;怎么解决IDEA快速插入getset构造这些方法 解决&#xff1a; 1.winR打开搜索 2.osk回车 屏幕就出现了这样的一…...

【鸿蒙学习笔记】属性学习迭代笔记

这里写目录标题 TextImageColumnRow Text Entry Component struct PracExample {build() {Row() {Text(文本描述).fontSize(40)// 字体大小.fontWeight(FontWeight.Bold)// 加粗.fontColor(Color.Blue)// 字体颜色.backgroundColor(Color.Red)// 背景颜色.width(50%)// 组件宽…...

工具推荐:滴答清单

官网地址&#xff1a;DIDA:Todo list, checklist and task manager app for Android, iPhone and Web 使用近一个月&#xff0c;特别方便&#xff0c;使用感受非常棒&#xff0c;功能全面。 我主要用了以下功能&#xff1a; 1、每日事项提醒&#xff1a;写作&#xff0c;背字…...

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …...

Vue3 + Element Plus + TypeScript中el-transfer穿梭框组件使用详解及示例

使用详解 Element Plus 的 el-transfer 组件是一个强大的穿梭框组件&#xff0c;常用于在两个集合之间进行数据转移&#xff0c;如权限分配、数据选择等场景。下面我将详细介绍其用法并提供一个完整示例。 核心特性与用法 基本属性 v-model&#xff1a;绑定右侧列表的值&…...

MVC 数据库

MVC 数据库 引言 在软件开发领域,Model-View-Controller(MVC)是一种流行的软件架构模式,它将应用程序分为三个核心组件:模型(Model)、视图(View)和控制器(Controller)。这种模式有助于提高代码的可维护性和可扩展性。本文将深入探讨MVC架构与数据库之间的关系,以…...

oracle与MySQL数据库之间数据同步的技术要点

Oracle与MySQL数据库之间的数据同步是一个涉及多个技术要点的复杂任务。由于Oracle和MySQL的架构差异&#xff0c;它们的数据同步要求既要保持数据的准确性和一致性&#xff0c;又要处理好性能问题。以下是一些主要的技术要点&#xff1a; 数据结构差异 数据类型差异&#xff…...

新能源汽车智慧充电桩管理方案:新能源充电桩散热问题及消防安全监管方案

随着新能源汽车的快速普及&#xff0c;充电桩作为核心配套设施&#xff0c;其安全性与可靠性备受关注。然而&#xff0c;在高温、高负荷运行环境下&#xff0c;充电桩的散热问题与消防安全隐患日益凸显&#xff0c;成为制约行业发展的关键瓶颈。 如何通过智慧化管理手段优化散…...

04-初识css

一、css样式引入 1.1.内部样式 <div style"width: 100px;"></div>1.2.外部样式 1.2.1.外部样式1 <style>.aa {width: 100px;} </style> <div class"aa"></div>1.2.2.外部样式2 <!-- rel内表面引入的是style样…...

【学习笔记】深入理解Java虚拟机学习笔记——第4章 虚拟机性能监控,故障处理工具

第2章 虚拟机性能监控&#xff0c;故障处理工具 4.1 概述 略 4.2 基础故障处理工具 4.2.1 jps:虚拟机进程状况工具 命令&#xff1a;jps [options] [hostid] 功能&#xff1a;本地虚拟机进程显示进程ID&#xff08;与ps相同&#xff09;&#xff0c;可同时显示主类&#x…...

Selenium常用函数介绍

目录 一&#xff0c;元素定位 1.1 cssSeector 1.2 xpath 二&#xff0c;操作测试对象 三&#xff0c;窗口 3.1 案例 3.2 窗口切换 3.3 窗口大小 3.4 屏幕截图 3.5 关闭窗口 四&#xff0c;弹窗 五&#xff0c;等待 六&#xff0c;导航 七&#xff0c;文件上传 …...

【Nginx】使用 Nginx+Lua 实现基于 IP 的访问频率限制

使用 NginxLua 实现基于 IP 的访问频率限制 在高并发场景下&#xff0c;限制某个 IP 的访问频率是非常重要的&#xff0c;可以有效防止恶意攻击或错误配置导致的服务宕机。以下是一个详细的实现方案&#xff0c;使用 Nginx 和 Lua 脚本结合 Redis 来实现基于 IP 的访问频率限制…...

在鸿蒙HarmonyOS 5中使用DevEco Studio实现企业微信功能

1. 开发环境准备 ​​安装DevEco Studio 3.1​​&#xff1a; 从华为开发者官网下载最新版DevEco Studio安装HarmonyOS 5.0 SDK ​​项目配置​​&#xff1a; // module.json5 {"module": {"requestPermissions": [{"name": "ohos.permis…...