【SpringAOP】转账问题演示及解决(Aop的引出:ConnectionUtils(ThreadLocal)+TransactionManager)
转账问题分析事务
accountDao中的使用的是Jdbctemplate
由于更新中途出现异常,导致source的金钱扣了却没有转账到target账户上!!!
转账问题解决
该解决方法代码量冗余,配置文件逻辑复杂,仍有巨大优化空间(代理模式加强方法)
工具类部分(通过ThreadLocal绑定线程上的Connection)
ConnectionUtils(通过ThreadLocal绑定对象)
package com.czy.utils;
import javax.sql.DataSource;
import java.sql.Connection;
/**
* 连接工具类
* 它用于从数据源获取一个连接,并且实现和线程的绑定
*/
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
//用spring注入此对象
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection(){
//1.先从ThreadLocal上获取
Connection conn = tl.get();
try {
//2.判断当前线程上是否有连接
if (conn == null) {
//3.从数据源获取一个连接,并且和线程绑定(存入ThreadLocal中)
conn = dataSource.getConnection();
tl.set(conn);
}
}catch (Exception exception){
throw new RuntimeException(exception);
}
//4.返回当前线程上的连接
return conn;
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
tl.remove();
}
}
TransactionManager(管理事务)
package com.czy.utils;
import java.sql.SQLException;
/**
* 事务管理相关的工具类,包含了开启事务,提交事务,回滚事务和释放连接
*/
public class TransactionManager {
//使用spring注入
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
connectionUtils.getThreadConnection().close(); //Connection还回连接池中
connectionUtils.removeConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
dao
package com.czy.dao.impl;
import com.czy.dao.AccountDao;
import com.czy.domain.Account;
import com.czy.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import java.sql.SQLException;
import java.util.List;
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements AccountDao {
private QueryRunner runner;
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAllAccount() {
try {
return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
public Account findAccountById(Integer id) {
try {
return runner.query(connectionUtils.getThreadConnection(),"select * from account where id = ?",new BeanHandler<Account>(Account.class),id);
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
public void saveAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money) values (?,?)",account.getName(),account.getMoney());
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public void updateAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),"update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public void deleteAccount(Integer id) {
try {
runner.update(connectionUtils.getThreadConnection(),"delete from account where id = ?",id);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public Account findAccountByName(String accountName) {
List<Account> accounts = null;
try {
accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ?",new BeanListHandler<Account>(Account.class),accountName);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if(accounts == null || accounts.size() == 0)
return null;
else if(accounts.size() > 1)
throw new RuntimeException("结果集不唯一");
return accounts.get(0);
}
}
service
package com.czy.service.impl;
import com.czy.dao.AccountDao;
import com.czy.domain.Account;
import com.czy.service.AccountService;
import com.czy.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class AccountServiceImpl implements AccountService {
private AccountDao dao;
private TransactionManager txManager;
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public void setDao(AccountDao dao) {
this.dao = dao;
}
public List<Account> findAllAccount() {
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
List<Account> accounts = dao.findAllAccount();
//3.提交事务
txManager.commit();
//4.返回结果
return accounts;
}catch(Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
txManager.release();
}
}
public Account findAccountById(Integer id) {
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
Account account = dao.findAccountById(id);
//3.提交事务
txManager.commit();
//4.返回结果
return account;
}catch(Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
txManager.release();
}
}
public void saveAccount(Account account) {
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
dao.saveAccount(account);
//3.提交事务
txManager.commit();
//4.返回结果
}catch(Exception e){
//5.回滚操作
txManager.rollback();
}finally {
//6.释放资源
txManager.release();
}
}
public void transfer(String sourceName, String targetName, Float money) {
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
//根据名称查询转出账户
Account source = dao.findAccountByName(sourceName);
//根据名称查询转入账户
Account target = dao.findAccountByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//转入账户减钱
target.setMoney(target.getMoney()+money);
//更新两者
dao.updateAccount(source);
int i = 1/0;
dao.updateAccount(target);
//3.提交事务
txManager.commit();
//4.返回结果
}catch(Exception e){
//5.回滚操作
txManager.rollback();
e.printStackTrace();
}finally {
//6.释放资源
txManager.release();
}
}
}
配置文件(依赖注入)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans file:///E:\JAVA\spring-framework-5.3.9\schema\beans\spring-beans.xsd">
<!--需要使用多例对象防止runner线程冲突-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
</bean>
<bean id="connectionUtils" class="com.czy.utils.ConnectionUtils">
<property name="dataSource" ref="druid"></property>
</bean>
<bean id="transactionManager" class="com.czy.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<bean id="DruidDataSourceFactory" class="com.czy.factory.DruidDataSourceFactory" init-method="init"></bean>
<bean id="druid" factory-bean="DruidDataSourceFactory" factory-method="getDataSource"></bean>
<bean id="accountDao" class="com.czy.dao.impl.AccountDaoImpl">
<property name="runner" ref="runner"></property>
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<bean id="accountService" class="com.czy.service.impl.AccountServiceImpl">
<property name="dao" ref="accountDao"></property>
<property name="txManager" ref="transactionManager"></property>
</bean>
</beans>
动态代理优化
package com.czy.factory;
import com.czy.domain.Account;
import com.czy.service.AccountService;
import com.czy.utils.TransactionManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
/**
* 用于创建Service的代理对象的工厂
*/
public class BeanFactory {
//通过spring获取
private AccountService accountService;
private TransactionManager txManager;
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
public AccountService getAccountService(){
final AccountService service = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
/**
* 添加事务的支持
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue = null;
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
rtValue = method.invoke(accountService,args);
//3.提交事务
txManager.commit();
//4.返回结果
return rtValue;
}catch(Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
txManager.release();
}
}
});
return service;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!