Spring--06自定义事务控制器

项目需求

实现账户间转账,能够实现事务的一致性,出现异常,事务回滚。

项目说明

  • 通过动态代理实现对转账方法进行事务控制
  • 基于XML的IoC配置
  • 自定义事务控制器
  • c3p0作为数据源
  • dbutils作为数据封装工具类
  • 自定义连接工具类
  • 生产方法增强的工厂类
  • 整合了spring和junit

新建实体类Account

package com.cncs.domain;

import java.io.Serializable;

public class Account  implements Serializable {
    private int id;
    private String name;
    private float money;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

新建业务层接口AccountService

package com.cncs.service;

import com.cncs.domain.Account;

import java.util.List;

/**
 * 账户的业务层接口
 */
public interface AccountService {
    void transfer(String sourceName,String targetName);
}

新建业务层实现类AccountServiceImpl

package com.cncs.service.impl;

import com.cncs.dao.AccountDao;
import com.cncs.domain.Account;
import com.cncs.service.AccountService;
import com.cncs.utils.TransactionManager;

import java.util.List;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(String sourceName, String targetName) {
        System.out.println("transfer...");
        //2.根据名称查找source账户
        Account sourceAccount = accountDao.findAccountByName(sourceName);
        //3.根据名称查找target账户
        Account targetAccount = accountDao.findAccountByName(targetName);
        //4.source账户减少钱
        sourceAccount.setMoney(sourceAccount.getMoney() - 200f);
        //5.target账户增加钱
        targetAccount.setMoney(targetAccount.getMoney() + 200f);
        //更新source账户
        accountDao.updateAccount(sourceAccount);

//        int a = 1 / 0;

        //更新target账户
        accountDao.updateAccount(targetAccount);
    }
}

新建持久层接口AccountDao

package com.cncs.dao;

import com.cncs.domain.Account;

import java.util.List;

/**
 * 账户持久层的接口
 */
public interface AccountDao {
 	
    Account findAccountByName(String accountName);

    void updateAccount(Account account);

}

新建持久层实现类AccountDaoImpl

package com.cncs.dao.impl;

import com.cncs.dao.AccountDao;
import com.cncs.domain.Account;
import com.cncs.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

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;
    }

    @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.size() == 1){
                return accounts.get(0);
            }else{
                throw new RuntimeException("查询结果不合法");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            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 (SQLException e) {
            e.printStackTrace();
        }
    }
}

新建连接工具类ConnectionUtils

package com.cncs.utils;

import javax.sql.DataSource;
import java.sql.Connection;

public class ConnectionUtils {

    private ThreadLocal<Connection> tl = new ThreadLocal<>();
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getThreadConnection() {
        try {
            //获取连接
            Connection connection = tl.get();
            //判断当前线程是否有连接
            if (connection == null) {
                //从数据源中获取一个连接,存入连接池
                connection = dataSource.getConnection();
                tl.set(connection);
            }
            return connection;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void removeConnection() {
        tl.remove();
    }
}

新建事务控制工具类TransactionManager

package com.cncs.utils;

import java.sql.Connection;
import java.sql.SQLException;

public class TransactionManager {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务
     */
    public void startTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 事务回滚
     */
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionUtils.getThreadConnection().commit(); //提交事务
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void release(){
        try {
            connectionUtils.getThreadConnection().close();  //关闭连接
            connectionUtils.removeConnection();             //将连接与线程解绑
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

新建对方法进行增强并获取对象的工厂类BeanFactory

package com.cncs.factory;

import com.cncs.service.AccountService;
import com.cncs.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class BeanFactory {

    private AccountService accountService = null;

    private TransactionManager transactionManager = null;

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public AccountService getAccountService() {
        AccountService accountService1 =(AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object returnVal = null;
                //1.开启事务
                transactionManager.startTransaction();
                try {
                    returnVal = method.invoke(accountService, args);
                    transactionManager.commit();
                } catch (Exception e) {
                    //6.事务回滚
                    transactionManager.rollback();
                    throw new RuntimeException(e);
                }finally {
                    transactionManager.release();
                }
                return returnVal;
            }
        });
        return accountService1;
    }
}

配置spring核心bean.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">
    <bean id="accountService" class="com.cncs.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <bean id="accountDao" class="com.cncs.dao.impl.AccountDaoImpl">
        <property name="runner" ref="runner"></property>
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </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://127.0.0.1:3306/spring_learn?useUnicode=true&amp;characterEncoding=utf-8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <bean id="transactionManager" class="com.cncs.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>

    <bean id="connectionUtils" class="com.cncs.utils.ConnectionUtils">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="beanFactory" class="com.cncs.factory.BeanFactory">
        <property name="transactionManager" ref="transactionManager"></property>
        <property name="accountService" ref="accountService"></property>
    </bean>

    <bean id="factoryAccountService" factory-bean="beanFactory" factory-method="getAccountService"></bean>

</beans>

新建测试类AccountTest

package com.cncs.test;

import com.cncs.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:bean.xml"})
public class AccountTest {

    @Autowired
    @Qualifier("factoryAccountService")
    private AccountService accountService;

    @Test
    public void testTransfer(){
        accountService.transfer("aaa","bbb");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值