银行转账案例
1 案例中添加转账方法并演示事务问题
1.打开IDEA工具如图所示的界面,点击Create New Project。
2.选择Maven工程和JDK的版本,如图所示:并点击Next。
3.填写项目名称和保存的地址,点击Finish。如图所示:
4.导入相应的依赖jar包的代码如下:
<?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.txw</groupId>
<artifactId>spring_01account</artifactId>
<version>1.0-SNAPSHOT</version>
<!--打包的方式 -->
<packaging>jar</packaging>
<dependencies>
<!--导入spring-context的依赖jar包坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--导入lombok的依赖jar包坐标-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--导入mysql的依赖jar包坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!--导入commons-dbutils的依赖jar包坐标-->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<!--导入spring-test的依赖jar包坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--导入c3p0的依赖jar包坐标-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!--导入junit的依赖jar包坐标-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!--导入junit的依赖jar包坐标-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
5.编写账户实体类的代码如下:
package com.txw.domain;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 账户的实体类
* @author:Adair
* @QQ:1578533828
*/
@Data // 自动生成set和get方法
@ToString // 重写toString方法
@SuppressWarnings("all") // 注解警告信息
public class Account implements Serializable {
private Integer id; // 账户的id
private String name; // 账户的名称
private Float money; // 账户的金额
}
6.编写账户的业务层接口代码如下:
package com.txw.service;
import com.txw.domain.Account;
import java.util.List;
/**
*账户的业务层接口
* @author:Adair
* @QQ:1578533828
*/
@SuppressWarnings("all") // 注解警告信息
public interface AccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 根据id查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
/**
* 根据id删除
* @param acccountId
*/
void deleteAccount(Integer accountId);
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
void transfer(String sourceName,String targetName,Float money);
}
7.编写账户的业务层实现类代码如下:
package com.txw.service.impl;
import com.txw.dao.AccountDao;
import com.txw.domain.Account;
import com.txw.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 账户的业务层实现类
* @author:Adair
* @QQ:1578533828
*/
@Service("accountService")
@SuppressWarnings("all") // 注解警告信息
public class AccountServiceImpl implements AccountService {
// 声明AccountDao业务对象
@Autowired
private AccountDao accountDao;
/**
* 查询所有
* @return
*/
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
/**
* 根据id查询一个
* @return
*/
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
/**
* 保存账户
* @param account
*/
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
/**
* 修改账户
* @param account
*/
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
/**
* 根据id删除
* @param acccountId
*/
public void deleteAccount(Integer accountId) {
accountDao.deleteAccount(accountId);
}
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer....");
// 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);
}
}
8.编写账户的持久层接口代码如下:
package com.txw.dao;
import com.txw.domain.Account;
import java.util.List;
/**
* 账户的持久层接口
* @author:Adair
* @QQ:1578533828
*/
@SuppressWarnings("all") // 注解警告信息
public interface AccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 根据id查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
/**
* 根据id删除
* @param acccountId
*/
void deleteAccount(Integer accountId);
/**
* 根据名称查询账户
* @param accountName
* @return 如果有唯一的一个结果就返回,如果没有结果就返回null
* 如果结果集超过一个就抛异常
*/
Account findAccountByName(String accountName);
}
9.编写账户的持久层实现类代码如下:
package com.txw.dao.impl;
import com.txw.dao.AccountDao;
import com.txw.domain.Account;
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;
/**
* 账户的持久层实现类
* @author:Adair
* @QQ:1578533828
*/
@Repository("accountDao")
@SuppressWarnings("all") // 注解警告信息
public class AccountDaoImpl implements AccountDao {
// 声明QueryRunner业务对象
@Autowired
private QueryRunner runner;
/**
* 查询所有
* @return
*/
public List<Account> findAllAccount() {
try{
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据id查询一个
* @return
*/
public Account findAccountById(Integer accountId) {
try{
return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 保存账户
* @param account
*/
public void saveAccount(Account account) {
try{
runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 修改账户
* @param account
*/
public void updateAccount(Account account) {
try{
runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据id删除
* @param accountId
*/
public void deleteAccount(Integer accountId) {
try{
runner.update("delete from account where id=?",accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据名称查询账户
* @param accountName
* @return
*/
public Account findAccountByName(String accountName) {
try{
List<Account> accounts = runner.query("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(e);
}
}
}
10.在resources目录下创建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: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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 告知spring在创建容器时要扫描的包 -->
<context:component-scan base-package="com.txw"></context:component-scan>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</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?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false"/>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans
11.编写测试的代码如下:
package com.txw.test;
import com.txw.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* 使用Junit单元测试:测试我们的配置
* @author:Adair
* @QQ:1578533828
*/
@SuppressWarnings("all") // 注解警告信息
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
// 声明AccountService业务对象
@Autowired
private AccountService as;
@Test
public void testTransfer(){
as.transfer("aaa","bbb",100f);
}
}
运行之前的数据库的数据如图所示:
运行结果如图所示:
运行之后的数据库的数据如图所示:说明转账成功!
如图所示,手动制造异常!
运行结果如图所示:
运行之后的数据库的数据如图所示:说明转账失败!不满足事务的一致性。
2 分析事务的问题并编写ConnectionUtils
1.事务控制,如图所示:
2.编写连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定代码如下:
package com.txw.utils;
import javax.sql.DataSource;
import java.sql.Connection;
/**
* 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
* @author:Adair
* @QQ:1578533828
*/
@SuppressWarnings("all") // 注解警告信息
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection() {
try{
// 1.先从ThreadLocal上获取
Connection conn = tl.get();
// 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();
}
}
3 编写事务管理工具类并分析连接和线程解
1.编写和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接的代码如下:
package com.txw.utils;
/**
* 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
* @author:Adair
* @QQ:1578533828
*/
@SuppressWarnings("all") // 注解警告信息
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
}catch (Exception 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 (Exception e){
e.printStackTrace();
}
}
}
4 编写业务层和持久层事务控制代码并配置spring的ioc
1.修改业务层实现类的代码如下:
package com.txw.service.impl;
import com.txw.dao.AccountDao;
import com.txw.domain.Account;
import com.txw.service.AccountService;
import com.txw.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 账户的业务层实现类
* 事务控制应该都是在业务层
* @author:Adair
* @QQ:1578533828
*/
@Service("accountService")
@SuppressWarnings("all") // 注解警告信息
public class AccountServiceImpl implements AccountService {
// 声明AccountDao业务对象
@Autowired
private AccountDao accountDao;
@Autowired
private TransactionManager transactionManager;
/**
* 查询所有
* @return
*/
public List<Account> findAllAccount() {
try {
// 1.开启事务
transactionManager.beginTransaction();
// 2.执行操作
List<Account> accounts = accountDao.findAllAccount();
// 3.提交事务
transactionManager.commit();
//4.返回结果
return accounts;
} catch (Exception e) {
// 5.回滚操作
transactionManager.rollback();
throw new RuntimeException(e);
} finally {
// 6.释放连接
transactionManager.release();
}
}
/**
* 根据id查询一个
* @return
*/
public Account findAccountById(Integer accountId) {
try {
// 1.开启事务
transactionManager.beginTransaction();
// 2.执行操作
Account account = accountDao.findAccountById(accountId);
// 3.提交事务
transactionManager.commit();
return account;
}catch (Exception e){
// 4.回滚操作
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
// 5.释放连接
transactionManager.release();
}
}
/**
* 保存账户
* @param account
*/
public void saveAccount(Account account) {
try {
// 1.开启事务
transactionManager.beginTransaction();
// 2.执行操作
accountDao.saveAccount(account);
// 3.提交事务
transactionManager.commit();
}catch (Exception e){
// 4.回滚操作
transactionManager.rollback();
}finally {
// 5.释放连接
transactionManager.release();
}
accountDao.saveAccount(account);
}
/**
* 修改账户
* @param account
*/
public void updateAccount(Account account) {
try {
// 1.开启事务
transactionManager.beginTransaction();
// 2.执行操作
accountDao.updateAccount(account);
// 3.提交事务
transactionManager.commit();
}catch (Exception e){
// 4.回滚操作
transactionManager.rollback();
}finally {
// 5.释放连接
transactionManager.release();
}
}
/**
* 根据id删除
* @param acccountId
*/
public void deleteAccount(Integer accountId) {
try {
// 1.开启事务
transactionManager.beginTransaction();
// 2.执行操作
accountDao.deleteAccount(accountId);
// 3.提交事务
transactionManager.commit();
}catch (Exception e){
// 4.回滚操作
transactionManager.rollback();
}finally {
// 5.释放连接
transactionManager.release();
}
}
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
public void transfer(String sourceName, String targetName, Float money) {
try {
// 1.开启事务
transactionManager.beginTransaction();
// 2.执行操作
System.out.println("transfer....");
// 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);
// 3.提交事务
transactionManager.commit();
}catch (Exception e){
// 4.回滚操作
transactionManager.rollback();
}finally {
// 5.释放连接
transactionManager.release();
}
}
}
2.修改账户持久层实现类的代码如下:
package com.txw.dao.impl;
import com.txw.dao.AccountDao;
import com.txw.domain.Account;
import com.txw.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;
/**
* 账户的持久层实现类
* @author:Adair
* @QQ:1578533828
*/
@Repository("accountDao")
@SuppressWarnings("all") // 注解警告信息
public class AccountDaoImpl implements AccountDao {
// 声明QueryRunner业务对象
@Autowired
private QueryRunner runner;
@Autowired
private ConnectionUtils connectionUtils;
/**
* 查询所有
* @return
*/
public List<Account> findAllAccount() {
try{
return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据id查询一个
* @return
*/
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(e);
}
}
/**
* 保存账户
* @param account
*/
public void saveAccount(Account account) {
try{
runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 修改账户
* @param account
*/
public void updateAccount(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);
}
}
/**
* 根据id删除
* @param accountId
*/
public void deleteAccount(Integer accountId) {
try{
runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据名称查询账户
* @param accountName
* @return
*/
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(e);
}
}
}
3.修改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: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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 告知spring在创建容器时要扫描的包 -->
<context:component-scan base-package="com.txw"></context:component-scan>
<!--配置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>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false"/>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置Connection的工具类 ConnectionUtils -->
<bean id="connectionUtils" class="com.txw.utils.ConnectionUtils">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器-->
<bean id="txManager" class="com.txw.utils.TransactionManager">
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
</beans>
运行之前的数据库的数据如图所示:
运行结果如图所示:
运行之后的数据库的数据如图所示:说明事务已经控制住!
5 代理分析
1.打开IDEA工具如图所示的界面,点击Create New Project。
2.选择Maven工程和JDK的版本,如图所示:并点击Next。
3.填写项目名称和保存的地址,点击Finish。如图所示:
4.导入相应的依赖jar包的代码如下:
<?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.txw</groupId>
<artifactId>spring_02proxy</artifactId>
<version>1.0-SNAPSHOT</version>
<!--打包的方式-->
<packaging>jar</packaging>
<dependencies>
<!--导入cglib的依赖jar包坐标-->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
</dependencies>
</project>
5.代理分析如图所示:
6 基于接口的动态代理回顾
1.编写对生产厂家要求的接口代码如下:
package com.txw.proxy;
/**
* 对生产厂家要求的接口
*/
@SuppressWarnings("all") // 注解警告信息
public interface IProducer {
/**
* 销售
* @param money
*/
public void saleProduct(float money);
/**
* 售后
* @param money
*/
public void afterService(float money);
}
2.编写一个生产者的代码如下:
package com.txw.proxy;
/**
* 一个生产者
*/
@SuppressWarnings("all") // 注解警告信息
public class Producer implements IProducer{
/**
* 销售
* @param money
*/
public void saleProduct(float money){
System.out.println("销售产品,并拿到钱:"+money);
}
/**
* 售后
* @param money
*/
public void afterService(float money){
System.out.println("提供售后服务,并拿到钱:"+money);
}
}
3.编写模拟一个消费者的代码如下:
package com.txw.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 模拟一个消费者
*/
@SuppressWarnings("all") // 注解警告信息
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
/**
* 动态代理:
* 特点:字节码随用随创建,随用随加载
* 作用:不修改源码的基础上对方法增强
* 分类:
* 基于接口的动态代理
* 基于子类的动态代理
* 基于接口的动态代理:
* 涉及的类:Proxy
* 提供者:JDK官方
* 如何创建代理对象:
* 使用Proxy类中的newProxyInstance方法
* 创建代理对象的要求:
* 被代理类最少实现一个接口,如果没有则不能使用
* newProxyInstance方法的参数:
* ClassLoader:类加载器
* 它是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。固定写法。
* Class[]:字节码数组
* 它是用于让代理对象和被代理对象有相同方法。固定写法。
* InvocationHandler:用于提供增强的代码
* 它是让我们写如何代理。我们一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。
* 此接口的实现类都是谁用谁写。
*/
IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
producer.getClass().getInterfaces(),
new InvocationHandler() {
/**
* 作用:执行被代理对象的任何接口方法都会经过该方法
* 方法参数的含义
* @param proxy 代理对象的引用
* @param method 当前执行的方法
* @param args 当前执行方法所需的参数
* @return 和被代理对象方法有相同的返回值
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 提供增强的代码
Object returnValue = null;
// 1.获取方法执行的参数
Float money = (Float)args[0];
// 2.判断当前方法是不是销售
if("saleProduct".equals(method.getName())) {
returnValue = method.invoke(producer, money*0.8f);
}
return returnValue;
}
});
proxyProducer.saleProduct(10000f);
}
}
运行结果如图所示:
7 基于子类的动态代理
1.编写一个生产者的代码如下:
package com.txw.cglib;
/**
* 一个生产者
*/
@SuppressWarnings("all") // 注解警告信息
public class Producer {
/**
* 销售
* @param money
*/
public void saleProduct(float money){
System.out.println("销售产品,并拿到钱:"+money);
}
/**
* 售后
* @param money
*/
public void afterService(float money){
System.out.println("提供售后服务,并拿到钱:"+money);
}
}
2.编写一个消费者的代码如下:
package com.txw.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 模拟一个消费者
*/
@SuppressWarnings("all") // 注解警告信息
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
/**
* 动态代理:
* 特点:字节码随用随创建,随用随加载
* 作用:不修改源码的基础上对方法增强
* 分类:
* 基于接口的动态代理
* 基于子类的动态代理
* 基于接口的动态代理:
* 涉及的类:Proxy
* 提供者:JDK官方
* 如何创建代理对象:
* 使用Proxy类中的newProxyInstance方法
* 创建代理对象的要求:
* 被代理类最少实现一个接口,如果没有则不能使用
* newProxyInstance方法的参数:
* ClassLoader:类加载器
* 它是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。固定写法。
* Class[]:字节码数组
* 它是用于让代理对象和被代理对象有相同方法。固定写法。
* InvocationHandler:用于提供增强的代码
* 它是让我们写如何代理。我们一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。
* 此接口的实现类都是谁用谁写。
*/
IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
producer.getClass().getInterfaces(),
new InvocationHandler() {
/**
* 作用:执行被代理对象的任何接口方法都会经过该方法
* 方法参数的含义
* @param proxy 代理对象的引用
* @param method 当前执行的方法
* @param args 当前执行方法所需的参数
* @return 和被代理对象方法有相同的返回值
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 提供增强的代码
Object returnValue = null;
// 1.获取方法执行的参数
Float money = (Float)args[0];
// 2.判断当前方法是不是销售
if("saleProduct".equals(method.getName())) {
returnValue = method.invoke(producer, money*0.8f);
}
return returnValue;
}
});
proxyProducer.saleProduct(10000f);
}
}
8 使用动态代理实现事务控制
1.编写账户实体类的代码如下:
package com.txw.domain;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 账户的实体类
* @author:Adair
* @QQ:1578533828
*/
@Data // 自动生成set和get方法
@ToString // 重写toString方法
@SuppressWarnings("all") // 注解警告信息
public class Account implements Serializable {
private Integer id; // 账户的id
private String name; // 账户的名称
private Float money; // 账户的金额
}
2.编写账户的业务层接口代码如下:
package com.txw.service;
import com.txw.domain.Account;
import java.util.List;
/**
* 账户的业务层接口
*/
@SuppressWarnings("all") // 注解警告信息
public interface IAccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 根据id查询账户
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
/**
* 根据id删除账户
* @param acccountId
*/
void deleteAccount(Integer acccountId);
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
void transfer(String sourceName,String targetName,Float money);
}
3.编写账户的业务层实现类代码如下:
package com.txw.service.impl;
import com.txw.dao.IAccountDao;
import com.txw.domain.Account;
import com.txw.service.IAccountService;
import java.util.List;
/**
* 账户的业务层实现类
* 事务控制应该都是在业务层
*/
@SuppressWarnings("all") // 注解警告信息
public class AccountServiceImpl implements IAccountService{
// 声明IAccountDao业务对象
private IAccountDao accountDao;
/**
* set注入
* @param accountDao
*/
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
/**
* 查询所有
* @return
*/
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
/**
* 根据id查询账户
* @param accountId
* @return
*/
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
/**
* 保存账户
* @param account
*/
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
/**
* 修改账户
* @param account
*/
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
/**
* 根据id删除账户
* @param acccountId
*/
public void deleteAccount(Integer acccountId) {
accountDao.deleteAccount(acccountId);
}
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer....");
// 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);
}
}
4.编写账户的持久层接口代码如下:
package com.txw.dao;
import com.txw.domain.Account;
import java.util.List;
/**
* 账户的持久层接口
*/
@SuppressWarnings("all") // 注解警告信息
public interface IAccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 根据id查询账户
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
/**
* 根据id删除账户
* @param acccountId
*/
void deleteAccount(Integer acccountId);
/**
* 根据名称查询账户
* @param accountName
* @return 如果有唯一的一个结果就返回,如果没有结果就返回null
* 如果结果集超过一个就抛异常
*/
Account findAccountByName(String accountName);
}
5.编写账户的持久层实现类代码如下:
package com.txw.dao.impl;
import com.txw.utils.ConnectionUtils;
import com.txw.dao.IAccountDao;
import com.txw.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
/**
* 账户的持久层实现类
*/
@SuppressWarnings("all") // 注解警告信息
public class AccountDaoImpl implements IAccountDao {
// 声明QueryRunner业务对象
private QueryRunner runner;
// 声明ConnectionUtils业务对象
private ConnectionUtils connectionUtils;
/**
* set注入
* @param runner
*/
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
/**
* set注入
* @param connectionUtils
*/
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 查询所有
* @return
*/
public List<Account> findAllAccount() {
try{
return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据id查询账户
* @param accountId
* @return
*/
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(e);
}
}
/**
* 保存账户
* @param account
*/
public void saveAccount(Account account) {
try{
runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 修改账户
* @param account
*/
public void updateAccount(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);
}
}
/**
* 根据id删除账户
* @param accountId
*/
public void deleteAccount(Integer accountId) {
try{
runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据名称查询账户
* @param accountName
* @return
*/
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(e);
}
}
}
6.在resources目录下创建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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置代理的service-->
<bean id="proxyAccountService" factory-bean="beanFactory" factory-method="getAccountService"></bean>
<!--配置beanfactory-->
<bean id="beanFactory" class="com.txw.factory.BeanFactory">
<!-- 注入service -->
<property name="accountService" ref="accountService"></property>
<!-- 注入事务管理器 -->
<property name="txManager" ref="txManager"></property>
</bean>
<!-- 配置Service -->
<bean id="accountService" class="com.txw.service.impl.AccountServiceImpl">
<!-- 注入dao -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置Dao对象-->
<bean id="accountDao" class="com.txw.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.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置Connection的工具类 ConnectionUtils -->
<bean id="connectionUtils" class="com.txw.utils.ConnectionUtils">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器-->
<bean id="txManager" class="com.txw.utils.TransactionManager">
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
</beans>
7.编写用于创建Service的代理对象的工厂代码如下:
package com.txw.factory;
import com.txw.service.IAccountService;
import com.txw.utils.TransactionManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 用于创建Service的代理对象的工厂
*/
@SuppressWarnings("all") // 注解警告信息
public class BeanFactory {
// 声明IAccountService业务对象
private IAccountService accountService;
// 声明TransactionManager业务对象
private TransactionManager txManager;
/**
* set注入
* @param txManager
*/
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
/**
* set注入
* @param accountService
*/
public final void setAccountService(IAccountService accountService) {
this.accountService = accountService;
}
/**
* 获取Service代理对象
* @return
*/
public IAccountService getAccountService() {
return (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
new InvocationHandler() {
/**
* 添加事务的支持
*
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("test".equals(method.getName())){
return method.invoke(accountService,args);
}
Object rtValue = null;
try {
// 1.开启事务
txManager.beginTransaction();
// 2.执行操作
rtValue = method.invoke(accountService, args);
// 3.提交事务
txManager.commit();
// 4.返回结果
return rtValue;
} catch (Exception e) {
// 5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
} finally {
// 6.释放连接
txManager.release();
}
}
});
}
}
8.连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定代码如下:
package com.txw.utils;
import javax.sql.DataSource;
import java.sql.Connection;
/**
* 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
*/
@SuppressWarnings("all") // 注解警告信息
public class ConnectionUtils {
// 创建ThreadLocal实例对象t1
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
// 声明DataSource业务对象
private DataSource dataSource;
/**
* set注入
* @param dataSource
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection() {
try{
// 1.先从ThreadLocal上获取
Connection conn = tl.get();
// 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();
}
}
9.编写和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接的代码如下:
package com.txw.utils;
/**
* 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
*/
@SuppressWarnings("all") // 注解警告信息
public class TransactionManager {
// 声明ConnectionUtils业务对象
private ConnectionUtils connectionUtils;
/**
* set注入
* @param connectionUtils
*/
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
}catch (Exception 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 (Exception e){
e.printStackTrace();
}
}
}
10.编写测试的代码如下:
package com.txw.test;
import com.txw.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;
/**
* 使用Junit单元测试:测试我们的配置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
@Qualifier("proxyAccountService")
private IAccountService as;
@Test
public void testTransfer(){
as.transfer("aaa","bbb",100f);
}
}
运行之前数据库的数据如图所示:
运行结果如图所示:
运行之后数据库的数据如图所示: