Spring基于XML AOP事务控制

源码

代码测试

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.zjw</groupId>
<artifactId>day04_eesy_02account_aoptx_xml</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<encoding>UTF-8</encoding>
<spring.version>6.1.1</spring.version>
<lombok.version>1.18.30</lombok.version>
<mysql.version>8.0.33</mysql.version>
<dbutils.version>1.7</dbutils.version>
<c3p0.version>0.9.1.2</c3p0.version>
<junit.version>4.13.2</junit.version>
<aspectjweaver.version>1.9.21</aspectjweaver.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>${dbutils.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
</dependencies> </project>

Spring配置文件

<?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"
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"> <!-- 配置Service -->
<bean id="accountService" class="com.zjw.service.impl.AccountServiceImpl">
<!-- 注入dao -->
<property name="accountDao" ref="accountDao"/>
</bean> <!--配置Dao对象-->
<bean id="accountDao" class="com.zjw.dao.impl.AccountDaoImpl">
<!-- 注入QueryRunner -->
<property name="runner" ref="runner"/>
<property name="connectionUtils" ref="connectionUtils"/>
</bean> <!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"/> <!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/eesy_spring?useSSL=false&amp;serverTimeZone=Asia/Shanghai"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean> <!--配置Connection的工具类 ConnectionUtils-->
<bean id="connectionUtils" class="com.zjw.utils.ConnectionUtils">
<property name="dataSource" ref="dataSource"/>
</bean> <!--配置事务管理器-->
<bean id="txManager" class="com.zjw.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"/>
</bean> <!--配置aop-->
<aop:config>
<!--配置通用切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.zjw.service.impl.*.*(..))"/>
<aop:aspect id="txAdvice" ref="txManager">
<!--配置前置通知,开启事务-->
<aop:before method="beginTransaction" pointcut-ref="pt1"/>
<!--配置后置通知,提交事务-->
<aop:after-returning method="commit" pointcut-ref="pt1"/>
<!--配置异常通知,回滚事务-->
<aop:after-throwing method="rollback" pointcut-ref="pt1"/>
<!--配置最终通知,释放事务-->
<aop:after method="release" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>
</beans>

数据库连接工具类

package com.zjw.utils;

import lombok.Setter;

import javax.sql.DataSource;
import java.sql.Connection; /**
* @author zjw
*/
public class ConnectionUtils { private ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); @Setter
private DataSource dataSource; public Connection getThreadConnection(){
try {
//1、先从ThreadLocal上获取
Connection conn = tl.get();
//2、判断当前线程上是否有连接
if (conn == null){
//3、从数据源中获取一个连接,并且存入ThreadLocal中
conn = dataSource.getConnection();
tl.set(conn);
}
//4、返回当前线程上的连接
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
} /**
* 把连接和线程解绑
*/
public void removeConnection(){
tl.remove();
}
}

事务管理类,切面类

package com.zjw.utils;

import lombok.Setter;

/**
* 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
* @author zjw
*/
public class TransactionManager { @Setter
private ConnectionUtils connectionUtils; /**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
connectionUtils.getThreadConnection().close();
connectionUtils.removeConnection();
}catch (Exception e){
e.printStackTrace();
}
}
}

Dao层实现

package com.zjw.dao.impl;

import com.zjw.dao.IAccountDao;
import com.zjw.domain.Account;
import com.zjw.utils.ConnectionUtils;
import lombok.Setter;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler; import java.util.List; /**
* 账户的持久层实现类
* @author zjw
*/
@Setter
public class AccountDaoImpl implements IAccountDao { private QueryRunner runner;
private ConnectionUtils connectionUtils; @Override
public List<Account> findAllAccount() {
try{
return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
} @Override
public Account findAccountById(Integer accountId) {
try{
return runner.query(connectionUtils.getThreadConnection(),"select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
} @Override
public void saveAccount(Account account) {
try{
runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
}catch (Exception e) {
throw new RuntimeException(e);
}
} @Override
public void updateAccount(Account account) {
try{
runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}catch (Exception e) {
throw new RuntimeException(e);
}
} @Override
public void deleteAccount(Integer accountId) {
try{
runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
} @Override
public Account findAccountByName(String accountName) {
try{
List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ? ",new BeanListHandler<Account>(Account.class),accountName);
if (accounts==null || accounts.size()==0){
return null;
}
if (accounts.size() > 1){
throw new RuntimeException("结果集不唯一,数据有问题");
}
return accounts.get(0);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}

Service层实现

这里故意写1/0,来验证事务的回滚操作

package com.zjw.service.impl;

import com.zjw.dao.IAccountDao;
import com.zjw.domain.Account;
import com.zjw.service.IAccountService;
import lombok.Setter; import java.util.List; /**
* 账户的业务层实现类
* <p>
* 事务的控制应该都在业务层
* @author zjw
*/
public class AccountServiceImpl implements IAccountService { @Setter
private IAccountDao accountDao; @Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
} @Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
} @Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
} @Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
} @Override
public void deleteAccount(Integer accountId) {
accountDao.deleteAccount(accountId);
} @Override
public void transfer(String sourceName, String targetName, Float money) {
//2、执行操作
//2.1、根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.2、根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3、转出账户减钱
source.setMoney(source.getMoney() - money);
//2.4、转入账户加钱
target.setMoney(target.getMoney() + money);
//2.5、更新转出账户
accountDao.updateAccount(source); int i = 1 / 0; //2.6、更新转入账户
accountDao.updateAccount(target);
}
}

测试

package com.zjw.test;

import com.zjw.domain.Account;
import com.zjw.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /**
* 使用Junit单元测试:测试我们的配置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest { @Autowired
private IAccountService as; @Test
public void testTransfer() {
List<Account> accountList = as.findAllAccount();
for (Account account : accountList) {
System.out.println(account);
} as.transfer("aaa", "bbb", 100f);
}
}

结果

控制台打印异常,数据库数据回滚

java.lang.ArithmeticException: / by zero

Spring基于XML AOP事务控制的更多相关文章

  1. spring基于xml的事务控制

    opm配置 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http: ...

  2. spring基于注解的事务控制

    pom配置: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http ...

  3. spring基于xml的声明式事务控制配置步骤

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  4. spring 基于XML和注解的两种事务配置方式

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  5. spring 基于xml的申明式AspectH中的后置通知的返回值获取

    spring 基于xml的申明式AspectH中的后置通知的返回值获取 1. 配置文件 <aop:config> <aop:aspect ref="myAspect&quo ...

  6. spring 基于XML的申明式AspectJ通知的执行顺序

    spring 基于XML的申明式AspectJ通知的执行顺序 关于各种通知的执行顺序,结论:与配置文件中的申明顺序有关 1. XML文件配置说明 图片来源:<Java EE企业级应用开发教程&g ...

  7. 吴裕雄--天生自然JAVA SPRING框架开发学习笔记:Spring基于XML装配Bean

    Bean 的装配可以理解为依赖关系注入,Bean 的装配方式也就是 Bean 的依赖注入方式.Spring 容器支持多种形式的 Bean 的装配方式,如基于 XML 的 Bean 装配.基于 Anno ...

  8. spring基于XML的声明式事务控制

    <?xml version="1.0" encoding="utf-8" ?><beans xmlns="http://www.sp ...

  9. Spring 基于xml配置方式的事务

    参考前面的声明式事务的例子:http://www.cnblogs.com/caoyc/p/5632198.html 我们做了相应的修改.在dao中和service中的各个类中,去掉所有注解标签.然后为 ...

  10. Spring 基于xml配置方式的事务(14)

    参考前面的声明式事务的例子:http://www.cnblogs.com/caoyc/p/5632198.html 我们做了相应的修改.在dao中和service中的各个类中,去掉所有注解标签.然后为 ...

随机推荐

  1. 我们是如何解决abp身上的几个痛点

    大家好,我是张飞洪,感谢您的阅读,我会不定期和你分享学习心得,希望我的文章能成为你成长路上的垫脚石,让我们一起精进. abp框架在.net社区是spring一样的存在,用的人也非常多,毫无疑问,它确实 ...

  2. JUC并发—3.volatile和synchronized原理

    大纲 1.volatile关键字的使用例子 2.主内存和CPU的缓存模型 3.CPU高速缓存的数据不一致问题 4.总线锁和缓存锁及MESI缓存一致性协议 5.Java的内存模型JMM 6.JMM如何处 ...

  3. JUC并发—5.AQS源码分析一

    大纲 1.JUC中的Lock接口 2.如何实现具有阻塞或唤醒功能的锁 3.AQS抽象队列同步器的理解 4.基于AQS实现的ReentractLock 5.ReentractLock如何获取锁 6.AQ ...

  4. WPF DevExpress GridColumn ComboBox 显示选择内容的 TooTip

    实现显示当前选择的ComboBox中项的ToolTip信息: 1. 设置 GridColumn 的 CellTemplate 为 ComboBoxEdit , 然后自定义他的 ItemContaine ...

  5. startup_stm32f10x_xx.s 启动代码文件的选择

    网上查到的各个文件的解释是: startup_stm32f10x_cl.s 互联型的器件startup_stm32f10x_hd.s 大容量startup_stm32f10x_hd_vl.s 大容量s ...

  6. JS实现隐藏手机号码中间4位数

    代码COPY 3. 使用正则 function geTel(tel){ var reg = /^(\d{3})\d{4}(\d{4})$/; return tel.replace(reg, " ...

  7. Redis 大 Key 分析利器:支持 TOP N、批量分析与从节点优先

    背景 Redis 大 key 分析工具主要分为两类: 1. 离线分析 基于 RDB 文件进行解析,常用工具是 redis-rdb-tools(https://github.com/sripathikr ...

  8. Spark - [03] 资源调度模式

    题记部分 一.Local模式 1.1.概述 Local模式就是运行在一台计算机上的模式,通常就是用于在本机上练手和测试的. 可以通过以下几种方式设置Master (1)local:所欲计算都运行在一个 ...

  9. .net core 非阻塞的异步编程 及 线程调度过程

    本文主要分为三个部分: 1.语法格式 2.线程调度情况 3.编程注意事项 4.练一练 * 阅读提示 :鼠标悬停在 章节标题 上可见 文章目录 异步编程(Task Asynchronous Progra ...

  10. 工作必会的Nginx的启动安装和常用配置例子

    概述 由于自己的之前学习 nginx 只会简单使用,然后每次配置 nginx 都要找文档去了解怎么配置,有点麻烦,所以这里记录下一些常用的nginx 配置和配置的例子,到时候直接 copy 修改即可. ...