一、引入依赖
pom.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.william</groupId><artifactId>spring_day04_01_tx_aop_xml</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.4</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.9</version></dependency></dependencies></project>
二、目录结构
三、applicationContext.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:context="http://www.springframework.org/schema/context"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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><!--开启注解扫描--><context:component-scan base-package="com.william"></context:component-scan><!--创建QueryRunner--><bean id="QueryRunner" class="org.apache.commons.dbutils.QueryRunner"></bean><!--创建dataSource--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driverClass}"></property><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property></bean><!--引入属性文件--><context:property-placeholder location="classpath:db.properties"></context:property-placeholder><!--使用aop解决事务问题--><!--配置切面:切入点,增强--><!--增强:事务管理--><bean id="transactionManager" class="com.william.utils.TransactionManager"></bean><!--aop配置--><aop:config><!--配置切面: ref 关联增强对象--><aop:aspect ref="transactionManager"><!--配置切入点--><aop:pointcut id="pc" expression="execution(* com.william.service.Impl.*.*(..))"></aop:pointcut><!--织入--><aop:before method="beganTransaction" pointcut-ref="pc"></aop:before><aop:after-returning method="Commit" pointcut-ref="pc"></aop:after-returning><aop:after-throwing method="rollBack" pointcut-ref="pc"></aop:after-throwing><aop:after method="release" pointcut-ref="pc"></aop:after></aop:aspect></aop:config>
</beans>
四、Class文件
1.AccountDaoImpl
代码:
package com.william.Dao.Impl;import com.william.Dao.AccountDao;
import com.william.domain.Account;
import com.william.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;import java.sql.SQLException;
import java.util.List;/*** @author :lijunxuan* @date :Created in 2019/5/27 16:00* @description :* @version: 1.0*/
@Repository
public class AccountDaoImpl implements AccountDao {@AutowiredConnectionUtils connectionUtils;@AutowiredQueryRunner queryRunner;@Overridepublic Account findByUserName(String username ) {String sql="select * from account where name = ?";try {return queryRunner.query(connectionUtils.getThreadConnection(),sql,new BeanHandler<>(Account.class),username);} catch (SQLException e) {e.printStackTrace();}return null;}@Overridepublic void Update(Account account) {String sql =" update account set money = ? where id =?";Object [] params= {account.getMoney(),account.getId()};try {queryRunner.update(connectionUtils.getThreadConnection(),sql,params);} catch (SQLException e) {e.printStackTrace();}}
}
2.AccountServiceImpl
package com.william.service.Impl;import com.william.Dao.AccountDao;
import com.william.domain.Account;
import com.william.service.AccountService;
import com.william.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @author :lijunxuan* @date :Created in 2019/5/27 16:14* @description :* @version: 1.0*/
@Service
public class AccountServiceImpl implements AccountService {@AutowiredAccountDao accountDao;@Overridepublic void transfer(String FromMoney, String ToMoney, Float money) {//开启事务:transactionManager//查询账户名称 两个账户名称Account FromuserName = accountDao.findByUserName(FromMoney);Account ToUserName = accountDao.findByUserName(ToMoney);//修改金额FromuserName.setMoney(FromuserName.getMoney()-money);ToUserName.setMoney(ToUserName.getMoney()+money);//int i=1/0;//修改账户表accountDao.Update(FromuserName);accountDao.Update(ToUserName);}
}
3.Utils工具类
(1)ConnectionUtils
package com.william.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;/*** @author :lijunxuan* @date :Created in 2019/5/27 16:50* @description :* @version: 1.0*/
@Component
public class ConnectionUtils {private ThreadLocal<Connection> t1=new ThreadLocal();@AutowiredDataSource dataSource;/*** 用来获取线程中连接对象* 1, 在第一次访问该方法时, 线程中没有对象,先获取一个,放入线程*/public Connection getThreadConnection(){//获取线程池中的对象Connection conn = t1.get();if (conn==null){try {conn = dataSource.getConnection();t1.set(conn);} catch (SQLException e) {e.printStackTrace();}}return conn;}/*** 移除线程*/public void remove(){t1.remove();}
}
(2)TransactionManager
package com.william.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.sql.SQLException;/*** @author :lijunxuan* @date :Created in 2019/5/27 16:50* @description :* @version: 1.0*/
@Component
public class TransactionManager {@AutowiredConnectionUtils connectionUtils;//开启事务public void beganTransaction(){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().setAutoCommit(true);connectionUtils.getThreadConnection().close();connectionUtils.remove();} catch (SQLException e) {e.printStackTrace();}}
}
4.TestTrasfer测试类
package com.william;import com.william.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*** @author :lijunxuan* @date :Created in 2019/5/27 16:22* @description :* @version: 1.0*/
@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestTrasfer {@AutowiredAccountService accountService;@Testpublic void testTrasferMoney(){accountService.transfer("william","william-Li",500f);}
}