一、基于xml的spring aop事务控制
1、创建maven项目并导入jar包的坐标
2、在domain包下创建账户实体类Account
package com.wedu.spring10.domain;
import java.io.Serializable;
/**
* 账户实体
*/
public class Account implements Serializable{
private Integer id;
private Integer uid;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
3、在dao包下创建持久层接口IAccountDao并添加CRUD方法
package com.wedu.spring10.dao;
import com.wedu.spring10.domain.Account;
import java.util.List;
/**
* 账户持久层接口
*/
public interface IAccountDao {
/**
* 查询所有账户
* @return
*/
List<Account> findAllAccount();
/**
* 添加账户
* @param account
*/
void saveAccount(Account account);
/**
* 修改账户
* @param account
*/
void updateAccount(Account account);
/**
* 根据id查询账户
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 删除账户
* @param id
*/
void deleteAccount(Integer id);
}
4、在dao包下创建持久层接口的实现类AccountDaoImpl并实现CRUD方法
package com.wedu.spring10.dao.impl;
import com.wedu.spring10.dao.IAccountDao;
import com.wedu.spring10.domain.Account;
import com.wedu.spring10.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 IAccountDao {
private QueryRunner runner;
private ConnectionUtils connectionUtils;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
@Override
public List<Account> findAllAccount() {
try {
return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void saveAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),"insert into account value(?,?,?)",account.getId(),account.getUid(),account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void updateAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),"update account set money=? where id=?",account.getMoney(),account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountById(Integer id) {
try {
return runner.query(connectionUtils.getThreadConnection(),"select * from account where id=?", new BeanHandler<Account>(Account.class), id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteAccount(Integer id) {
try {
runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",id);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
5、在service包下创建业务层接口IAccountService并添加CRUD方法
package com.wedu.spring10.service;
import com.wedu.spring10.domain.Account;
import java.util.List;
/**
* 账户业务层接口
*/
public interface IAccountService {
/**
* 查询所有账户
* @return
*/
List<Account> findAllAccount();
/**
* 添加账户
* @param account
*/
void saveAccount(Account account);
/**
* 修改账户
* @param account
*/
void updateAccount(Account account);
/**
* 根据id查询账户
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 删除账户
* @param id
*/
void deleteAccount(Integer id);
/**
* 转账业务
* @param sourceId 转出账户
* @param targetId 转入账户
* @param money 转账金额
*/
void transfer(Integer sourceId,Integer targetId, Double money);
}
6、在service包下创建业务层接口的实现类AccountServiceImpl并实现CRUD方法
package com.wedu.spring10.service.impl;
import com.wedu.spring10.dao.IAccountDao;
import com.wedu.spring10.domain.Account;
import com.wedu.spring10.service.IAccountService;
import java.util.List;
/**
* 账户业务层接口实现
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void deleteAccount(Integer id) {
accountDao.deleteAccount(id);
}
@Override
public void transfer(Integer sourceId, Integer targetId, Double money) {
//1、根据id查询转出账户
Account source = accountDao.findAccountById(sourceId);
//2、根据id查询转入账户
Account target = accountDao.findAccountById(targetId);
//3、设置转出金额
source.setMoney(source.getMoney() - money);
//4、设置转入金额
target.setMoney(target.getMoney() + money);
//5、更新转出账户
accountDao.updateAccount(source);
//int i = 10/0;
//6、更新转入账户
accountDao.updateAccount(target);
}
}
7、在utils包下创建数据库连接工具类ConnectionUtils
package com.wedu.spring10.utils;
import javax.sql.DataSource;
import java.sql.Connection;
/**
* 数据库连接工具类
*/
public class ConnectionUtils {
private DataSource dataSource;
private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection() {
try{
//1.先从ThreadLocal上获取
Connection conn = threadLocal.get();
//2.判断当前线程上是否有连接
if (conn == null) {
//3.从数据源中获取一个连接,并且存入ThreadLocal中
conn = dataSource.getConnection();
threadLocal.set(conn);
}
//4.返回当前线程上的连接
return conn;
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
threadLocal.remove();
}
}
8、在utils包下创建事务管理工具类TransactionManager
package com.wedu.spring10.utils;
import java.sql.SQLException;
/**
* 事务管理工具类
*/
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 (Exception e){
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release() {
try {
connectionUtils.getThreadConnection().close();//还回连接池中
connectionUtils.removeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
9、在resources下创建配置文件bean.xml并配置spring ioc和aop及事务
<?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.wedu.spring10.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!--配置dao-->
<bean id="accountDao" class="com.wedu.spring10.dao.impl.AccountDaoImpl">
<property name="runner" ref="runner"/>
<property name="connectionUtils" ref="connectionUtils"/>
</bean>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"/>
<!-- 配置Connection的工具类 ConnectionUtils-->
<bean id="connectionUtils" class="com.wedu.spring10.utils.ConnectionUtils">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置事务管理器-->
<bean id="txManager" class="com.wedu.spring10.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"/>
</bean>
<!--配置aop-->
<aop:config>
<!--配置通用切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.wedu.spring10.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>
10、在测试模块中创建测试类AccountServiceTest并编写转账业务测试方法
package com.wedu.spring10.service;
import com.wedu.spring10.domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* 基于xml的spring的事务控制测试
*/
public class AccountServiceTest {
private IAccountService accountService;
@Before
public void init() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
accountService = ac.getBean("accountService", IAccountService.class);
}
/**
* 查询所有账户
*/
@Test
public void testFindAllAccount() {
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
/**
* 转账
*/
@Test
public void testTransfer() {
accountService.transfer(1,2,100d);
}
}
二、基于注解的spring aop事务控制
1、创建maven项目并导入jar包的坐标
2、在domain包下创建账户实体类Account
package com.wedu.spring11.domain;
import java.io.Serializable;
/**
* 账户实体
*/
public class Account implements Serializable{
private Integer id;
private Integer uid;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
3、在dao包下创建持久层接口IAccountDao并添加CRUD方法
package com.wedu.spring11.dao;
import com.wedu.spring11.domain.Account;
import java.util.List;
/**
* 账户持久层接口
*/
public interface IAccountDao {
/**
* 查询所有账户
* @return
*/
List<Account> findAllAccount();
/**
* 添加账户
* @param account
*/
void saveAccount(Account account);
/**
* 修改账户
* @param account
*/
void updateAccount(Account account);
/**
* 根据id查询账户
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 删除账户
* @param id
*/
void deleteAccount(Integer id);
}
4、在dao包下创建持久层接口的实现类AccountDaoImpl并实现CRUD方法
package com.wedu.spring11.dao.impl;
import com.wedu.spring11.dao.IAccountDao;
import com.wedu.spring11.domain.Account;
import com.wedu.spring11.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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
/**
* 账户持久层接口实现
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Autowired
private ConnectionUtils connectionUtils;
@Override
public List<Account> findAllAccount() {
try {
return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void saveAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),"insert into account value(?,?,?)",account.getId(),account.getUid(),account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void updateAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),"update account set money=? where id=?",account.getMoney(),account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountById(Integer id) {
try {
return runner.query(connectionUtils.getThreadConnection(),"select * from account where id=?", new BeanHandler<Account>(Account.class), id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteAccount(Integer id) {
try {
runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",id);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
5、在service包下创建业务层接口IAccountService并添加CRUD方法
package com.wedu.spring11.service;
import com.wedu.spring11.domain.Account;
import java.util.List;
/**
* 账户业务层接口
*/
public interface IAccountService {
/**
* 查询所有账户
* @return
*/
List<Account> findAllAccount();
/**
* 添加账户
* @param account
*/
void saveAccount(Account account);
/**
* 修改账户
* @param account
*/
void updateAccount(Account account);
/**
* 根据id查询账户
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 删除账户
* @param id
*/
void deleteAccount(Integer id);
/**
* 转账业务
* @param sourceId 转出账户
* @param targetId 转入账户
* @param money 转账金额
*/
void transfer(Integer sourceId, Integer targetId, Double money);
}
6、在service包下创建业务层接口的实现类AccountServiceImpl并实现CRUD方法
package com.wedu.spring11.service.impl;
import com.wedu.spring11.dao.IAccountDao;
import com.wedu.spring11.domain.Account;
import com.wedu.spring11.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 账户业务层接口实现
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void deleteAccount(Integer id) {
accountDao.deleteAccount(id);
}
@Override
public void transfer(Integer sourceId, Integer targetId, Double money) {
//1、根据id查询转出账户
Account source = accountDao.findAccountById(sourceId);
//2、根据id查询转入账户
Account target = accountDao.findAccountById(targetId);
//3、设置转出金额
source.setMoney(source.getMoney() - money);
//4、设置转入金额
target.setMoney(target.getMoney() + money);
//5、更新转出账户
accountDao.updateAccount(source);
//int i = 1/0;
//6、更新转入账户
accountDao.updateAccount(target);
}
}
7、在utils包下创建数据库连接工具类ConnectionUtils
package com.wedu.spring11.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
/**
* 数据库连接工具类
*/
@Component("connectionUtils")
public class ConnectionUtils {
@Autowired
private DataSource dataSource;
private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection() {
try{
//1.先从ThreadLocal上获取
Connection conn = threadLocal.get();
//2.判断当前线程上是否有连接
if (conn == null) {
//3.从数据源中获取一个连接,并且存入ThreadLocal中
conn = dataSource.getConnection();
threadLocal.set(conn);
}
//4.返回当前线程上的连接
return conn;
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
threadLocal.remove();
}
}
8、在utils包下创建事务管理工具类TransactionManager
package com.wedu.spring11.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
/**
* 事务管理工具类
*/
@Component("txManager")
@Aspect
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
@Pointcut("execution(* com.wedu.spring11.service.impl.*.*(..))")
private void pt1(){}
/**
* 开启事务
*/
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 (Exception e){
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release() {
try {
connectionUtils.getThreadConnection().close();//还回连接池中
connectionUtils.removeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Around("pt1()")
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
//1.获取参数
Object[] args = pjp.getArgs();
//2.开启事务
this.beginTransaction();
//3.执行方法
rtValue = pjp.proceed(args);
//4.提交事务
this.commit();
//返回结果
return rtValue;
}catch (Throwable e){
//5.回滚事务
this.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
this.release();
}
}
}
9、在resources下创建配置文件bean.xml并配置spring ioc扫描和开启spring aop的注解
<?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"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.wedu.spring11"/>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--开启spring对注解AOP的支持-->
<aop:aspectj-autoproxy/>
</beans>
10、在测试模块中创建测试类AccountServiceTest并编写转账业务测试方法
package com.wedu.spring11.service;
import com.wedu.spring11.domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* 基于注解的spring事务控制测试
*/
public class AccountServiceTest {
private IAccountService accountService;
@Before
public void init() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
accountService = ac.getBean("accountService", IAccountService.class);
}
/**
* 查询所有账户
*/
@Test
public void testFindAllAccount() {
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
/**
* 转账
*/
@Test
public void testTransfer() {
accountService.transfer(1,2,100d);
}
}