Spring使用AOP的事务管理

配置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">

<!--配置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="connectionUtils"></property>
</bean>

<!--配置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.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?serverTimezone=Asia/Shanghai&amp;characterEncoding=utf8&amp;useSSL=false"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>

<!--配置connection的工具类 ConnectionUtils-->
<bean id="connectionUtils" class="com.itheima.utils.ConnectionUtils" >
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>

<!--配置事务管理器-->
<bean id="transactionManager" class="com.itheima.utils.TransactionManager">
<!--注入ConnectionUtils-->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>

<!--配置aop-->
<aop:config>
<!--配置通用的切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
<aop:aspect id="txAdvice" ref="transactionManager">
<!--配置前置通知,开启事务-->
<aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before>
<!--配置后置通知,提交事务-->
<aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning>
<!--配置异常通知,回滚事务-->
<aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing>
<!--配置最终通知,释放连接-->
<aop:after method="release" pointcut-ref="pt1"></aop:after>

</aop:aspect>
</aop:config>
</beans>

工具类:ConnectionUtils
package com.itheima.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import javafx.scene.chart.PieChart;

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

/**
* @Author: lijiahao
* @Description: 连接工具类,用于从数据源中获取连接,并且实现和线程的绑定
* @Data: Create in 0:35 2020/2/7
* @Modified By:
*/
public class ConnectionUtils {
private ThreadLocal tl = new ThreadLocal();

private DataSource dataSource;

public void setDataSource(ComboPooledDataSource dataSource){
this.dataSource = dataSource;
}
/**
* @Author Lijiahao
* @Description :获取当前线程上的连接
* @Date 0:39 2020/2/7
* @Param []
* @return Connenction
**/

public Connection getThreadConnection(){
//1.先从ThreadLocal上获取
Connection conn = (Connection) tl.get();
//2.判断当前线程是否有连接
try {
if(conn == null){
//3.从数据中获取一个连接,并且存入ThreadLocal中
conn = dataSource.getConnection();
tl.set(conn);
}
//4.返回当前线程上的连接
return conn;
} catch (SQLException e) {
throw new RuntimeException();
}
}

//把连接和线程解绑
public void removeConnection(){
tl.remove();
}

}

工具类:TransactionManager
package com.itheima.utils;

import java.sql.SQLException;

/**
* @Author: lijiahao
* @Description: 和事务管理相关的工具类,包含开启事务,事务提交,事务回滚
* @Data: Create in 0:50 2020/2/7
* @Modified By:
*/
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();
}
}
}

实体类:
package com.itheima.domain;

/**
* @Author: lijiahao
* @Description: 账户的实体类
* @Data: Create in 0:10 2020/2/6
* @Modified By:
*/
public class Account {

private Integer id;
private String name;
private Float money;

@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + 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;
}
}

service实现类
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import com.itheima.utils.TransactionManager;

import java.util.List;

/**
* @Author: lijiahao
* @Description:
* @Data: Create in 0:16 2020/2/6
* @Modified By:
*/
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) {
System.out.println("trans......");
//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 i = 1/0;

//2.6.更新转入账户
accountDao.updateAccount(target);

}
}

Dao实现类
package com.itheima.dao.impl;

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

import javax.management.RuntimeMBeanException;
import java.sql.SQLException;
import java.util.List;

/**
* @Author: lijiahao
* @Description:
* @Data: Create in 0:21 2020/2/6
* @Modified By:
*/
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;
}

public List<Account> findAllAccount() {
try {
return runner.query(connectionUtils.getThreadConnection(),"select * from account", new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException();
}
}

public Account findAccountById(Integer accountid) {
try {
return runner.query(connectionUtils.getThreadConnection(),"select * from account where id = ?", new BeanHandler<Account>(Account.class), accountid);
} catch (Exception e) {
throw new RuntimeException();
}
}


public void saveAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money) values (?,?)", account.getName(),account.getMoney());
} catch (SQLException e) {
e.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 e) {
e.printStackTrace();
}
}

public void deleteAccount(Integer accountid) {
try {
runner.update(connectionUtils.getThreadConnection(),"delete from account where id = ?", accountid);
} catch (SQLException e) {
e.printStackTrace();
}
}

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 == null || accounts.size() == 0){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
} catch (Exception e) {
throw new RuntimeException();
}
}

测试
package com.itheima.test;

import com.itheima.domain.Account;
import com.itheima.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;

import java.util.List;

/**
* @Author: lijiahao
* @Description: 使用junit测试配置
* @Data: Create in 0:59 2020/2/6
* @Modified By:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private IAccountService as;

@Test
public void testTransfer(){
as.transfer("aaa", "bbb", 100f);
}
}


}

猜你喜欢

转载自www.cnblogs.com/lijiahaoAA/p/12286680.html