基于XML的AOP实现事务控制
pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
</dependencies>
Account.java
package com.how2java.domain;
import java.io.Serializable;
public class Account implements Serializable{
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer 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 +
'}';
}
}
IAccountDao.java
package com.how2java.dao;
import com.how2java.domain.Account;
import java.util.List;
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 查询所有账户
* @return
*/
List<Account> findAll();
/**
* 根据id查询账户
* @param id
* @return
*/
Account findById(Integer id);
/**
* 保存账户
* @param account
*/
void save(Account account);
/**
* 更新账户
* @param account
*/
void update(Account account);
/**
* 删除账户
* @param id
*/
void delete(Integer id);
/**
* 根据名称查询账户
* @param name
* @return 如果有唯一的结果,就返回;如果没有结果,就返回null;如果有多个结果,就抛出异常。
*/
Account findByName(String name);
}
AccountDaoImpl.java
package com.how2java.dao.impl;
import com.how2java.dao.IAccountDao;
import com.how2java.domain.Account;
import com.how2java.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao{
private QueryRunner runner;
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
@Override
public List<Account> findAll() {
try{
return runner.query(connectionUtils.getThreadConnection(), "select * from account", new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findById(Integer id) {
try{
return runner.query(connectionUtils.getThreadConnection(), "select * from account where id = ?", id, new BeanHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void save(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 update(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 delete(Integer id) {
try{
runner.update(connectionUtils.getThreadConnection(), "delete from account where id = ?", id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findByName(String name) {
try{
List<Account> accounts = runner.query(connectionUtils.getThreadConnection(), "select * from account where name = ?", name, new BeanListHandler<Account>(Account.class));
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);
}
}
}
IAccountService.java
package com.how2java.service;
import com.how2java.domain.Account;
import java.util.List;
/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 查询所有账户
* @return
*/
List<Account> findAll();
/**
* 根据id查询账户
* @param id
* @return
*/
Account findById(Integer id);
/**
* 保存账户
* @param account
*/
void save(Account account);
/**
* 更新账户
* @param account
*/
void update(Account account);
/**
* 删除账户
* @param id
*/
void delete(Integer id);
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转帐金额
*/
void transfer(String sourceName, String targetName, Float money);
}
AccountServiceImpl.java
package com.how2java.service.impl;
import com.how2java.dao.IAccountDao;
import com.how2java.domain.Account;
import com.how2java.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> findAll() {
return accountDao.findAll();
}
@Override
public Account findById(Integer id) {
return accountDao.findById(id);
}
@Override
public void save(Account account) {
accountDao.save(account);
}
@Override
public void update(Account account) {
accountDao.update(account);
}
@Override
public void delete(Integer id) {
accountDao.delete(id);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer...");
//1.根据名称查询转出账户
Account source = accountDao.findByName(sourceName);
//2.根据名称查询转入账户
Account target = accountDao.findByName(targetName);
//3.转出账户减钱
source.setMoney(source.getMoney()-money);
// int i = 1/0;
//4.转入账户加钱
target.setMoney(target.getMoney()+money);
//5.更新转出账户
accountDao.update(source);
//6.更新转入账户
accountDao.update(target);
}
}
ConnectionUtils.java
package com.how2java.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;
}
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection() {
//1.从ThreadLocal上获取连接
Connection conn = tl.get();
try {
//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();
}
}
TransactionManager.java
package com.how2java.utils;
/**
* 和事务管理相关的工具类,包含开启事务、提交事务、回滚事务以及释放连接
*/
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void begin() {
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 提交事务
*/
public void commit() {
try {
connectionUtils.getThreadConnection().commit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 回滚事务
*/
public void rollback() {
try {
connectionUtils.getThreadConnection().rollback();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 释放连接
*/
public void release() {
try {
connectionUtils.getThreadConnection().close();//返回连接池
connectionUtils.removeConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置业务层对象-->
<bean id="accountService" class="com.how2java.service.impl.AccountServiceImpl">
<!--注入持久层对象-->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置TransactionManager对象-->
<bean id="transactionManager" class="com.how2java.utils.TransactionManager">
<!--注入ConnectionUtils对象-->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--持久层对象-->
<bean id="accountDao" class="com.how2java.dao.impl.AccountDaoImpl">
<!--注入QueryRunner对象-->
<property name="runner" ref="runner"></property>
<!--注入ConnectionUtils对象-->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置QueryRunner对象-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>
<!--配置ConnectionUtils对象-->
<bean id="connectionUtils" class="com.how2java.utils.ConnectionUtils">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</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/spring?characterEncoding=UTF-8"></property>
<property name="user" value="root"></property>
<property name="password" value="admin"></property>
</bean>
<!--配置AOP-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="tm" expression="execution(* com.how2java.service.impl.*.*(..))"></aop:pointcut>
<!--配置切面-->
<aop:aspect id="tmAdvice" ref="transactionManager">
<!--配置前置通知,开启事务-->
<aop:before method="begin" pointcut-ref="tm"></aop:before>
<!--配置后置通知,提交事务-->
<aop:after-returning method="commit" pointcut-ref="tm"></aop:after-returning>
<!--配置异常通知,回滚事务-->
<aop:after-throwing method="rollback" pointcut-ref="tm"></aop:after-throwing>
<!--配置最终通知,释放连接-->
<aop:after method="release" pointcut-ref="tm"></aop:after>
</aop:aspect>
</aop:config>
</beans>
TestAccount.java
package com.how2java;
import com.how2java.service.IAccountService;
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")
/**
* 使用junit测试配置
*/
public class TestAccount {
@Autowired
private IAccountService as;
@Test
public void testTransfer() throws Exception {
as.transfer("aaa", "bbb", 100F);
}
}
基于注解的AOP实现事务控制
pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
</dependencies>
Account.java
package com.how2java.domain;
import java.io.Serializable;
public class Account implements Serializable{
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer 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 +
'}';
}
}
IAccountDao.java
package com.how2java.dao;
import com.how2java.domain.Account;
import java.util.List;
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 查询所有账户
* @return
*/
List<Account> findAll();
/**
* 根据id查询账户
* @param id
* @return
*/
Account findById(Integer id);
/**
* 保存账户
* @param account
*/
void save(Account account);
/**
* 更新账户
* @param account
*/
void update(Account account);
/**
* 删除账户
* @param id
*/
void delete(Integer id);
/**
* 根据名称查询账户
* @param name
* @return 如果有唯一的结果,就返回;如果没有结果,就返回null;如果有多个结果,就抛出异常。
*/
Account findByName(String name);
}
AccountDaoImpl.java
package com.how2java.dao.impl;
import com.how2java.dao.IAccountDao;
import com.how2java.domain.Account;
import com.how2java.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.util.List;
/**
* 账户的持久层实现类
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao{
@Autowired
private QueryRunner runner;
@Autowired
private ConnectionUtils connectionUtils;
@Override
public List<Account> findAll() {
try{
return runner.query(connectionUtils.getThreadConnection(), "select * from account", new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findById(Integer id) {
try{
return runner.query(connectionUtils.getThreadConnection(), "select * from account where id = ?", id, new BeanHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void save(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 update(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 delete(Integer id) {
try{
runner.update(connectionUtils.getThreadConnection(), "delete from account where id = ?", id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findByName(String name) {
try{
List<Account> accounts = runner.query(connectionUtils.getThreadConnection(), "select * from account where name = ?", name, new BeanListHandler<Account>(Account.class));
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);
}
}
}
IAccountService.java
package com.how2java.service;
import com.how2java.domain.Account;
import java.util.List;
/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 查询所有账户
* @return
*/
List<Account> findAll();
/**
* 根据id查询账户
* @param id
* @return
*/
Account findById(Integer id);
/**
* 保存账户
* @param account
*/
void save(Account account);
/**
* 更新账户
* @param account
*/
void update(Account account);
/**
* 删除账户
* @param id
*/
void delete(Integer id);
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转帐金额
*/
void transfer(String sourceName, String targetName, Float money);
}
AccountServiceImpl.java
package com.how2java.service.impl;
import com.how2java.dao.IAccountDao;
import com.how2java.domain.Account;
import com.how2java.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> findAll() {
return accountDao.findAll();
}
@Override
public Account findById(Integer id) {
return accountDao.findById(id);
}
@Override
public void save(Account account) {
accountDao.save(account);
}
@Override
public void update(Account account) {
accountDao.update(account);
}
@Override
public void delete(Integer id) {
accountDao.delete(id);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer...");
//1.根据名称查询转出账户
Account source = accountDao.findByName(sourceName);
//2.根据名称查询转入账户
Account target = accountDao.findByName(targetName);
//3.转出账户减钱
source.setMoney(source.getMoney()-money);
int i = 1/0;
//4.转入账户加钱
target.setMoney(target.getMoney()+money);
//5.更新转出账户
accountDao.update(source);
//6.更新转入账户
accountDao.update(target);
}
}
SpringConfiguration.java
package com.how2java.config;
import org.springframework.context.annotation.*;
/**
* 父配置类
*/
@Configuration
@ComponentScan("com.how2java")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}
JdbcConfig.java
package com.how2java.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
/**
* 子配置类
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
@Bean(name = "dataSource")
public DataSource createDataSource() {
try{
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
ConnectionUtils.java
package com.how2java.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 {
private ThreadLocal<Connection> tl = new ThreadLocal<>();
@Autowired
private 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);
}
//4.返回当前线程上的连接
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 把连接和线程解绑
*/
public void removeConnection() {
tl.remove();
}
}
TransactionManager.java
package com.how2java.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 和事务管理相关的工具类,包含开启事务、提交事务、回滚事务以及释放连接
*/
@Component("txManager")
@Aspect
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
@Pointcut("execution(* com.how2java.service.impl.*.*(..))")
private void pt(){
}
/**
* 开启事务
*/
// @Before("pt()")
public void begin() {
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 提交事务
*/
// @AfterReturning("pt()")
public void commit() {
try {
connectionUtils.getThreadConnection().commit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 回滚事务
*/
// @AfterThrowing("pt()")
public void rollback() {
try {
connectionUtils.getThreadConnection().rollback();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 释放连接
*/
// @After("pt()")
public void release() {
try {
connectionUtils.getThreadConnection().close();//返回连接池
connectionUtils.removeConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Around("pt()")
public Object aroundAdvice(ProceedingJoinPoint pjp) {
Object rtValue = null;
try{
//1.获取参数
Object[] args = pjp.getArgs();
//2.开启事务
this.begin();
//3.执行方法
rtValue = pjp.proceed(args);
//4.提交事务
this.commit();
//5.返回结果
return rtValue;
} catch (Throwable t) {
//6.回滚事务
this.rollback();
throw new RuntimeException(t);
} finally {
//7.释放连接
this.release();
}
}
}
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=admin
TestAccount.java
package com.how2java;
import com.how2java.config.SpringConfiguration;
import com.how2java.service.IAccountService;
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(classes = SpringConfiguration.class)
/**
* 使用junit测试配置
*/
public class TestAccount {
@Autowired
private IAccountService as;
@Test
public void testTransfer() throws Exception {
as.transfer("aaa", "bbb", 100F);
}
}