package com.hope.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;
/**
* @author newcityman
* @date 2019/11/21 - 20:52
*/
@Component("txManager")
@Aspect
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
@Pointcut("execution(* com.hope.service.impl.*.*(..))")
private void pt(){ }
/**
* 开启事务
*/
public void beainTransaction(){
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();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Around("pt()")
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object rtValue=null;
try {
//1、获取参数
Object[] args = pjp.getArgs();
//2、开启事务
this.beainTransaction();
//3、执行方法
rtValue=pjp.proceed(args);
//4、提交事务
this.commit();
//5、返回结果
return rtValue;
} catch (Throwable e) {
//6、回滚事务
this.rollback();
throw new RuntimeException("事务提交有误,请联系管理员");
} finally {
//7、释放资源
this.release();
}
}
<?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.hope"/>
<!--配置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/easy"/>
<property name="user" value="root"/>
<property name="password" value="123"/>
</bean>
<!--开启spring对注解AOP的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
}