使用Spring与JDK动态代理实现事务管理

embedded/2024/9/22 18:35:05/

使用Spring与JDK动态代理实现事务管理

在现代企业级应用开发中,事务管理是一项关键的技术,它可以保证一系列操作要么全部成功,要么全部失败,从而确保数据的一致性和完整性。Spring框架提供了强大的事务管理能力,但有时为了更细粒度地控制事务边界,我们可能需要自己实现事务管理逻辑。本文将介绍如何结合Spring框架和JDK动态代理技术来实现一个简单的事务管理系统。

引言

在本示例中,我们将创建一个基于Spring框架的应用程序,该程序包含一个账户服务接口(IAccountService),以及其实现类(AccountServiceImp)。为了增强该服务的事务处理能力,我们将创建一个工厂类(ProxyBeanFactory),它会为IAccountService生成一个动态代理对象,该对象能够在调用真实服务方法前后自动开启和提交事务。

XML配置

首先,我们需要配置Spring的bean定义。下面是一个简化版的Spring配置文件示例:

<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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!-- 数据源配置略 --><!-- QueryRunner配置略 --><!-- 连接工具类配置略 --><!-- 事务工具类配置略 --><!-- 数据访问层配置略 --><!-- 业务逻辑层配置略 --><bean id="proxyService" class="org.example.service.IAccountService" factory-bean="factory" factory-method="createProxy"></bean><bean id="factory" class="org.example.factory.ProxyBeanFactory"><property name="transactionUtil" ref="transactionUtil"></property><property name="toProxyService" ref="service"/></bean><!-- 控制器配置略 --></beans>

如上所示,ProxyBeanFactory将创建一个实现了IAccountService接口的代理对象,并且会在执行业务逻辑之前和之后自动管理事务。

动态代理工厂类

接下来,我们来看一下ProxyBeanFactory类的具体实现:

java">package org.example.factory;import org.example.service.IAccountService;
import org.example.util.TransactionUtil;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public class ProxyBeanFactory {private IAccountService toProxyService;private TransactionUtil transactionUtil;public void setToProxyService(IAccountService toProxyService) {this.toProxyService = toProxyService;}public void setTransactionUtil(TransactionUtil transactionUtil) {this.transactionUtil = transactionUtil;}public IAccountService createProxy() {return (IAccountService) Proxy.newProxyInstance(toProxyService.getClass().getClassLoader(),toProxyService.getClass().getInterfaces(),new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {Object result = null;try {transactionUtil.beginTx();result = method.invoke(toProxyService, args);transactionUtil.commitTx();} catch (Exception e) {transactionUtil.rollbackTx();} finally {transactionUtil.closeTx();}return result;}});}
}

ProxyBeanFactory类的核心在于createProxy方法,它使用JDK动态代理机制来创建代理对象。当任何IAccountService接口方法被调用时,都会触发InvocationHandler中的invoke方法,从而开启事务、执行业务逻辑并最终提交或回滚事务。

示例代码:

applicationContext.xml:

  <!-- 加载资源文件 --><context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder><!-- 注入数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${msg1}"/><property name="jdbcUrl" value="${msg2}"/><property name="user" value="${msg3}"/><property name="password" value="${msg4}"/></bean><bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"><constructor-arg name="ds" ref="dataSource"/></bean><!-- 连接工具类 --><bean id="connectionUtil" class="org.example.util.ConnectionUtil"><property name="dataSource" ref="dataSource"/></bean><!-- 事务工具类 --><bean id="transactionUtil" class="org.example.util.TransactionUtil"><property name="connectionUtil" ref="connectionUtil"/></bean><bean id="mapperImp" class="org.example.dao.AccountMapperImp"><property name="queryRunner" ref="queryRunner"></property><property name="connectionUtil" ref="connectionUtil"></property></bean><bean id="service" class="org.example.service.AccountServiceImp"><property name="dao" ref="mapperImp"></property></bean><bean id="proxyService" class="org.example.service.IAccountService" factory-bean="factory" factory-method="createProxy"></bean><bean id="factory" class="org.example.factory.ProxyBeanFactory"><property name="transactionUtil" ref="transactionUtil"></property><property name="toProxyService" ref="service"/></bean><bean id="controller" class="org.example.controller.AccountControllerImp"><property name="service" ref="proxyService"></property></bean></beans>

ProxyBeanFactory:

java">public class ProxyBeanFactory {IAccountService toProxyService;;//装配事务工具类TransactionUtil transactionUtil;public void setAccountServiceImp(IAccountService accountServiceImp) {toProxyService = accountServiceImp;}public void setToProxyService(IAccountService toProxyService) {this.toProxyService = toProxyService;}public void setTransactionUtil(TransactionUtil transactionUtil) {this.transactionUtil = transactionUtil;}public IAccountService getAccountServiceImp() {return toProxyService;}//2.创建代理public IAccountService createProxy(){IAccountService proxy = (IAccountService) Proxy.newProxyInstance(toProxyService.getClass().getClassLoader(), toProxyService.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {Object obj = null;try {transactionUtil.beginTx();obj = method.invoke(toProxyService, args);transactionUtil.commitTx();} catch (Exception e) {e.printStackTrace();transactionUtil.rollbackTx();} finally {transactionUtil.closeTx();}return obj;}});return proxy;}
}

http://www.ppmy.cn/embedded/92858.html

相关文章

24 - clearerr()函数

文章目录 1 函数原型2 参数3 返回值 1 函数原型 clearerr()函数&#xff1a;清除指定流stream的错误指示符&#xff0c;函数原型如下&#xff1a; void clearerr ( FILE * stream );cstdio库描述如下&#xff1a; Clear error indicators 1. Resets both the error and the …

YOLOv8进 | 检测头 | 小目标遮挡物性能提升的检测头Detect_MultiSEAM【完整代码】

秋招面试专栏推荐 &#xff1a;深度学习算法工程师面试问题总结【百面算法工程师】——点击即可跳转 &#x1f4a1;&#x1f4a1;&#x1f4a1;本专栏所有程序均经过测试&#xff0c;可成功执行&#x1f4a1;&#x1f4a1;&#x1f4a1; 专栏目录 &#xff1a;《YOLOv8改进有效…

OSPF 命令 Default-router-advertise 之 always 选项解析

1、关于 default-route-advertise 命令 Ospf 是可以通过 import-route 命令引入外部路由的&#xff0c;但很少有人会注意到&#xff0c;在默认情况下&#xff0c;ospf 是不会引入来自外部路由的缺省路由的。 但 ospf 有一个变通的方法&#xff0c;就是通过 default-route-adv…

AI+ 如何重塑技术生产力

在21世纪的科技浪潮中&#xff0c;人工智能&#xff08;AI&#xff09;作为一股不可忽视的力量&#xff0c;正以前所未有的速度渗透并重塑着各行各业的生产力格局。从智能制造到智慧农业&#xff0c;从金融服务到医疗健康&#xff0c;AI技术的应用不仅极大地提升了生产效率&…

Docker深入讲解

Docker深入讲解 目录 概述Docker基本概念 2.1 什么是Docker2.2 Docker的核心组件2.3 Docker与传统虚拟化技术的比较 Docker安装与配置 3.1 安装Docker3.2 配置Docker3.3 验证Docker安装 Docker镜像 4.1 什么是Docker镜像4.2 获取和管理镜像4.3 Dockerfile的使用4.4 构建镜像 …

JVM性能监控

一、jvisualvm jdk官方提供了监控JVM性能的工具jvisualvm&#xff0c;安装JDK之后&#xff0c;在安装目录下的bin目录中&#xff0c;找到jvisualvm.exe双击即可打开。 打开后的界面如下&#xff1a; 首次打开时候需要安装GC插件 Cmd 启动 jvisualvm 工具->插件 如果 503 …

二叉树:镜像树,子结构,二叉树转链表,二叉树的倒数K个数,对称,Z型打印

1.把一棵二叉树转换为它的镜像树。 void mirror_tree(TreeNode *root) {if(rootNULL) return ;TreeNode *temproot->right;root->rightroot->left;root->lefttemp;mirror_tree(root->right);mirror_tree(root->left);}2、输入两棵二叉树A&#xff0c;B&…

机器学习——第五章

目录 1 神经元模型2 感知机与多层网络3 误差逆传播算法&#xff08;BP&#xff09;4 全局最小与局部极小5 其他常见神经网络5.1 RBF网络5.2 ART网络5.3 SOM网络5.4 级联相关网络5.5 Elman网络5.6 Boltzmann机 6 深度学习 1 神经元模型 神经网络是由具有适应性的简单单元组成的…