转账操作小案例,通过动态代理实现事务与业务层的分离
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
/**
* 注意:此处配置了两个Service对象,在创建Service对象时需要通过@Qualifer指明使用哪儿个配置。
*/
<!--配置代理的Service对象-->
<bean id="proxyAccountService" factory-bean="beanFactory" factory-method="getAccountService"></bean>
<!--配置beanFactory-->
<bean id="beanFactory" class="com.itheima.factory.BeanFactory">
<!--注入service-->
<property name="accountService" ref="accountService"></property>
<!--注入事务管理器-->
<property name="txManager" ref="txManager"></property>
</bean>
<!-- 配置Service对象 -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<!-- 注入dao对象 -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置dao对象-->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<!--注入QueryRunner对象-->
<property name="runner" ref="runner"></property>
<!--注入ConnectionUtils-->
<property name="connectionUtils" ref="connectionUtil"></property>
</bean>
<!--配置QueryRunner对象-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner"></bean>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!--配置Connection的工具类-->
<bean id="connectionUtil" class="com.itheima.utils.ConnectionUtils">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务管理器-->
<bean id="txManager" class="com.itheima.utils.TransactionManager">
<!--注入ConnectionUtils-->
<property name="connectionUtils" ref="connectionUtil"></property>
</bean>
</beans>
用于创建Service的代理对象的工厂(通过动态代理增强,给Service类添加上事务控制的功能)
public class BeanFactory {
private IAccountService accountService; // 需要代理的对象
private TransactionManager txManager; // 需要使用到的事务控制类
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
/**
* 获取Service的代理对象
* @return
*/
public IAccountService getAccountService(){
IAccountService as = (IAccountService) 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 as;
}
/**
*
* @param accountService
*/
public final void setAccountService(IAccountService accountService) {
this.accountService = accountService;
}
}
业务层Java代码
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao){
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(Integer accountId) {
accountDao.deleteAccount(accountId);
}
public void transfer(String sourceName, String targetName, Float money) {
// 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 a = 1/0; // 连接池和线程绑定+事务的控制,解决了程序运行异常导致的转账操作失败而不回滚操作,导致程序运行一半。
// 2.6 更新转入账户
accountDao.updateAccount(target);
}
}
连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 获取当前线程上的连接
* @return
*/
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();
}
}
事务管理相关的工具类,它包含了:开启事务、提交事务、回滚事务和释放连接
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
// 释放连接,将连接还给连接池
connectionUtils.getThreadConnection().close();
// 解绑连接池
connectionUtils.removeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Junit单元测试
@Autowired
@Qualifier("proxyAccountService") // 指明选择哪儿个配置
private IAccountService as;
@Test
public void testTransfer(){
as.transfer("bbb","aaa",100f);
}