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.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://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 {
	//注入 JdbcTemplate
	private JdbcTemplate jdbcTemplate;

	public UserDaoImpl(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public 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.mfbz.cn/a/782193.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

软件架构之数据库系统(2)

软件架构之数据库系统&#xff08;2&#xff09; 3.4 事务管理3.4.1 并发控制3.4.2 故障与恢复 3.5 备份与恢复3.6分布式数据库系统3.6.1分布式数据库的概念3.6.2 分布式数据库的架构 3.7 数据仓库3.7.1 数据仓库的概念3.7.2数据仓库的结构3.7.3 数据仓库的实现方法 3.8 数据挖…

超高精电容传感器PCAP01调试+LABVIEW数据可视化调试手记

PCAP01超高精电容传感芯片STM32LabView可视化 文章目录 PCAP01超高精电容传感芯片STM32LabView可视化一、PCAP01介绍1.1、PCAP01引脚定义1.2、电容测量1.3、温度测量1.4、PCAP典型测试电路 二、PCAP01的STM32驱动2.1、SPI协议配置2.2、PCAP01浮空电容测量内部温度测量操作流程 …

计算机系统简述

目标 计算机世界并非如此神秘。相反&#xff0c;计算机是非常“确定”的一个系统&#xff0c;即在任何时候&#xff0c;在相同的方法、相同的状态下&#xff08;当然还包括相同的起始条件&#xff09;&#xff0c;同样的问题必然获得相同的结果。其实&#xff0c;计算机并不是…

前端实现无缝自动滚动动画

1. 前言: 前端使用HTMLCSS实现一个无缝滚动的列表效果 示例图: 2. 源码 html部分源码: <!--* Author: wangZhiyu <w3209605851163.com>* Date: 2024-07-05 23:33:20* LastEditTime: 2024-07-05 23:49:09* LastEditors: wangZhiyu <w3209605851163.com>* File…

强化学习的数学原理:时序差分算法

概述 之前第五次课时学习的 蒙特卡洛 的方法是全课程当中第一次介绍的第一种 model-free 的方法&#xff0c;而本次课的 Temporal-Difference Learning 简称 TD learning &#xff08;时序差分算法&#xff09;就是第二种 model-free 的方法。而对于 蒙特卡洛方法其是一种 non…

使用大漠插件进行京东联盟转链

由于之前开发了一套使用api转链的接口在前面几个月失效了。因为京东联盟系统升级&#xff0c;导致之前可以转的链接现在必须要升级权限才可以。但是升级条件对于我们这些自己买东西转链想省点钱的人来说基本上达不到。 所以&#xff0c;基于这种情况。我之前研究过大漠插件&am…

数据库的学习(4)

一、题目 1、创建数据表qrade: CREATE TABLE grade(id INT NOT NULL,sex CHAR(1),firstname VARCHAR(20)NOT NULL,lastname VARCHAR(20)NOT NULL,english FLOAT,math FLOAT,chinese FLOAT ); 2、向数据表grade中插入几条数据: (3,mAllenwiiliam,88.0,92.0 95.0), (4,m,George&…

第七篇——攻谋篇:兵法第一原则——兵力原则,以多胜少

目录 一、背景介绍二、思路&方案三、过程1.思维导图2.文章中经典的句子理解3.学习之后对于投资市场的理解4.通过这篇文章结合我知道的东西我能想到什么&#xff1f; 四、总结五、升华 一、背景介绍 微观层面上&#xff0c;也有很多值得深度思考的问题 二、思路&方案 …

用ThreadLocal解决线程隔离问题

存在的以下代码所示的线程隔离问题&#xff1a; package study.用ThreadLocal解决线程隔离问题;/*线程隔离 - 在多线程并发场景下&#xff0c;每个线程的变量都应该是相互独立的线程A&#xff1a;设置&#xff08;变量1&#xff09; 获取&#xff08;变量1&#xff09;线程B&a…

瑞芯微rk356x TF卡烧写选择指定的屏幕打印烧写的过程

rk356x中TF卡烧写屏幕选择 1、开发环境2、问题描述3、解决办法4、总结5、 图片展示1、开发环境 系统:linux系统 芯片:356x 显示:多屏显示(HDMI, MIPI, LVDS, EDP) 2、问题描述 由于在多屏显示的情况下,HDMI屏在LVDS、MIPI或者EDP协同下,默认情况下,在TF卡烧录过程中…

论文润色最强最实用ChatGPT提示词指令

大家好&#xff0c;感谢关注。我是七哥&#xff0c;一个在高校里不务正业&#xff0c;折腾学术科研AI实操的学术人。关于使用ChatGPT等AI学术科研的相关问题可以和作者七哥&#xff08;yida985&#xff09;交流&#xff0c;多多交流&#xff0c;相互成就&#xff0c;共同进步&a…

C++语言相关的常见面试题目(二)

1.vector底层实现原理 以下是 std::vector 的一般底层实现原理&#xff1a; 内存分配&#xff1a;当创建一个 std::vector 对象时&#xff0c;会分配一块初始大小的连续内存空间来存储元素。这个大小通常会随着 push_back() 操作而动态增加。 容量和大小&#xff1a;std::vec…

【Linux】进程间的通信----管道

&#x1f490; &#x1f338; &#x1f337; &#x1f340; &#x1f339; &#x1f33b; &#x1f33a; &#x1f341; &#x1f343; &#x1f342; &#x1f33f; &#x1f344;&#x1f35d; &#x1f35b; &#x1f364; &#x1f4c3;个人主页 &#xff1a;阿然成长日记 …

妈妈带女儿美在心里

在这个充满温情与惊喜的午后&#xff0c;阳光温柔地洒落在每一个角落&#xff0c;仿佛连空气弥漫着幸福的味道。就在这样一个平凡的时刻&#xff0c;一段关于爱与成长的温馨画面&#xff0c;悄然在网络上绽放&#xff0c;引爆了无数人的心弦——#奚梦瑶2岁女儿身高#&#xff0c…

在 VS Code 中自动化 Xcode 项目编译和调试

在 VS Code 中自动化 Xcode 项目编译和调试 在日常的开发工作中&#xff0c;Xcode 是 macOS、iOS、watchOS 和 tvOS 应用程序开发的主要工具。为了提高工作效率&#xff0c;许多开发者选择在 Visual Studio Code (VS Code) 中编辑代码&#xff0c;并希望能够直接从 VS Code 启…

【vue组件库搭建06】组件库构建及npm发包

一、格式化目录结构 根据以下图片搭建组件库目录 index.js作为入口文件&#xff0c;将所有组件引入&#xff0c;并注册组件名称 import { EButton } from "./Button"; export * from "./Button"; import { ECard } from "./Card"; export * fr…

网络通信总体框架

目录 网络通信 一、网络通信的定义与基本原理 二、网络通信的组成要素 三、网络通信的应用与发展 网络体系结构 一、网络体系结构的定义与功能 二、OSI七层参考模型 三、网络体系结构的重要性 网络核心与边缘 一、网络核心 1. 定义与功能 2. 组成部分 3. 技术特点 …

昇思25天学习打卡营第19天|LSTM+CRF序列标注

概述 序列标注指给定输入序列&#xff0c;给序列中每个Token进行标注标签的过程。序列标注问题通常用于从文本中进行信息抽取&#xff0c;包括分词(Word Segmentation)、词性标注(Position Tagging)、命名实体识别(Named Entity Recognition, NER)等。 条件随机场&#xff08…

01:spring

文章目录 一&#xff1a;常见面试题1&#xff1a;什么是Spring框架&#xff1f;1.1&#xff1a;spring官网中文1.2&#xff1a;spring官网英文 2&#xff1a;谈谈自己对于Spring IOC和AOP的理解2.1&#xff1a;IOCSpring Bean 的生命周期主要包括以下步骤&#xff1a; 2.2&…

国产化新标杆:TiDB 助力广发银行新一代总账系统投产上线

随着全球金融市场的快速发展和数字化转型的深入推进&#xff0c;金融科技已成为推动银行业创新的核心力量。特别是在当前复杂多变的经济环境下&#xff0c;银行业务的高效运作和风险管理能力显得尤为重要。总账系统作为银行会计信息系统的核心&#xff0c;承载着记录、处理和汇…