springAOP

简单转账功能

准备数据

# 删除spring_aop数据库
drop database if exists spring_aop;

# 创建spring_aop数据库
create database spring_aop;

# 使用spring_aop数据库
use spring_aop;

# 创建account表
create table account (
    id int(11) auto_increment primary key,
    accountNum varchar(20) default NULL,
    money int(8) default 0
);

# 新增数据
insert into account (accountNum, money) values
("622200001",1000),("622200002",1000);

导包

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.13.RELEASE</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
    <groupId>commons-dbutils</groupId>
    <artifactId>commons-dbutils</artifactId>
    <version>1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

配置文件

<?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:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       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/util
        https://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
       ">

    <!-- bean definitions here -->
    <context:component-scan base-package="dao"/>
    <context:component-scan base-package="services"/>
    <context:component-scan base-package="utils"/>

</beans>

配置数据

<!--配置QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"/>
<!-- 配置数据源 -->
<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_aop"></property>
    <property name="user" value="root"></property>
    <property name="password" value="123456"></property>
</bean>

代码编写
工具类

@Component
public class ConnectionUtils {
    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    @Autowired
    private ComboPooledDataSource dataSource;

    /**
     * 获得当前线程绑定的连接
     *
     * @return
     */
    public Connection getThreadConnection() {
        try {
            // 看线程是否绑了连接
            Connection conn = tl.get();
            if (conn == null) {
                // 从数据源获取一个连接
                conn = dataSource.getConnection();
                // 和线程局部变量  绑定
                tl.set(conn);
            }
            // 返回线程连接
            return tl.get();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 把连接和当前线程进行解绑
     */
    public void remove() {
        tl.remove();
    }
}

Account模块实体类:

public class Account {
    private Integer id;
    private String accountNum;
    private Integer money;
    // 省略getter&setter方法
}

Account模块Dao层:

public interface AccountDao {
    /**
     * 更新
     *
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据编号查询账户
     *
     * @param accountNum
     * @return 如果没有结果就返回null,如果结果集超过一个就抛异常,如果有唯一的一个结果就返回
     */
    Account findAccountByNum(String accountNum);
}

Account模块Dao层实现类:

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
    // 数据库查询工具类
    @Autowired
    private QueryRunner runner;
    // 数据库连接工具类
    @Autowired
    private ConnectionUtils connectionUtils;

    /**
     * 更新
     *
     * @param account
     */
    public void updateAccount(Account account) {
        try {
            runner.update(connectionUtils.getThreadConnection(),
                    "update account set accountNum=?,money=? where id=?",
                    account.getAccountNum(), account.getMoney(), account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据编号查询账户
     *
     * @param accountNum
     * @return 如果没有结果就返回null,如果结果集超过一个就抛异常,如果有唯一的一个结果就返回
     */
    public Account findAccountByNum(String accountNum) {
        List<Account> accounts = null;
        try {
            accounts = runner.query(connectionUtils.getThreadConnection(),
                    "select * from account where accountNum = ? ",
                    new BeanListHandler<Account>(Account.class),
                    accountNum);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if (accounts == null || accounts.size() == 0) {
            // 如果没有结果就返回null
            return null;
        } else if (accounts.size() > 1) {
            // 如果结果集超过一个就抛异常
            throw new RuntimeException("结果集不唯一,数据有问题");
        } else {
            // 如果有唯一的一个结果就返回
            return accounts.get(0);
        }
    }
}

Account模块Service层:

public interface AccountService {
    /**
     * 转账
     *
     * @param sourceAccount 转出账户
     * @param targetAccount 转入账户
     * @param money         转账金额
     */
    void transfer(String sourceAccount, String targetAccount, Integer money);
}

Account模块Service层实现类:

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    /**
     * 转账
     *
     * @param sourceAccount 转出账户
     * @param targetAccount 转入账户
     * @param money         转账金额
     */
    public void transfer(String sourceAccount, String targetAccount, Integer money) {
        // 查询原始账户
        Account source = accountDao.findAccountByNum(sourceAccount);
        // 查询目标账户
        Account target = accountDao.findAccountByNum(targetAccount);
        // 原始账号减钱
        source.setMoney(source.getMoney() - money);
        // 目标账号加钱
        target.setMoney(target.getMoney() + money);
        // 更新原始账号
        accountDao.updateAccount(source);
        // 更新目标账号
        accountDao.updateAccount(target);
        System.out.println("转账完毕");
    }
}

Account模块测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AccountTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer() {
        accountService.transfer("622200001", "622200002", 100);
    }
}

引入代理模式解决事务

代码实现
事务管理器:TransactionManager.java
此工具类主要作用是对数据库连接实现事务的开启,提交以及回滚
至于何时开启、提交、回滚事务,根据业务场景需要调用该类的方法

@Component
public class TransactionManager {
    // 数据库连接工具类
    @Autowired
    private ConnectionUtils connectionUtils;

    /**
     * 开启事务
     */
    public void beginTransaction() {
        try {
            System.out.println("开启事务");
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        try {
            System.out.println("提交事务");
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback() {
        try {
            System.out.println("回滚事务");
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    public void release() {
        try {
            System.out.println("释放连接");
            connectionUtils.getThreadConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        connectionUtils.removeConnection();
    }
}

事务代理工具类:TransactionProxyUtils

@Component
public class TransactionProxyUtils {
    //被代理的业务类接口
    @Autowired
    private AccountService accountService;
    //提供事务管理的工具类
    @Autowired
    private TransactionManager transactionManager;

    /**
     * 获取AccountService代理对象
     *
     * @return
     */
    public AccountService getAccountService() {
        return (AccountService) Proxy.newProxyInstance(
                accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 添加事务的支持
                     *
                     * @param proxy     被代理的对象实例本身
                     * @param method    被代理对象正在执行的方法对象
                     * @param args      正在访问的方法参数对象
                     * @return
                     * @throws Throwable
                     */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        //
                        Object rtValue = null;
                        try {
                            // 执行操作前开启事务
                            transactionManager.beginTransaction();
                            // 执行操作
                            rtValue = method.invoke(accountService, args);
                            // 执行操作后提交事务
                            transactionManager.commit();
                            // 返回结果
                            return rtValue;
                        } catch (Exception e) {
                            // 捕捉到异常执行回滚操作
                            transactionManager.rollback();
                            throw new RuntimeException(e);
                        } finally {
                            // 最终释放连接
                            transactionManager.release();
                        }
                        
                    }
                });

    }
}

核心配置文件:applicationContext.xml

//添加事务管理bean
<context:component-scan base-package="transaction"/>
配置代理Service

<!--配置代理的service-->
<bean id="transactionProxyAccountService" factory-bean="transactionProxyUtils" factory-method="getAccountService"/>

Account模块测试类:AccountTest.java

//将原本引入的AccountService实例改为AccountService的事务代理对象
@Qualifier("transactionProxyAccountService")


引入AOP(XML)

代码实现
1.删除事务代理工具类:TransactionProxyUtils.java

2.导入aspectjweaver包

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.3</version>
</dependency>

配置文件中添加 AOP

<!-- aop相关的节点配置 -->
<aop:config>
    <!-- 切入点  表示哪些类的哪些方法在执行的时候会应用Spring配置的通知进行增强 -->
    <aop:pointcut expression="execution ( * services.*.*(..))" id="pc"/>
    <!-- 配置切面类的节点  作用主要就是整合通知和切入点 -->
    <aop:aspect ref="transactionManager">
        <aop:before method="beginTransaction" pointcut-ref="pc"/>
        <aop:after-returning method="commit" pointcut-ref="pc"/>
        <aop:after method="release" pointcut-ref="pc"/>
        <aop:after-throwing method="rollback" pointcut-ref="pc"/>
    </aop:aspect>
</aop:config>

修改测试类代码

@Autowired
private AccountService accountService;

XML改注解(AOP)

删除aopxm配置

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

注释事务管理器类```

```java
@Component
@Aspect
public class TransactionManager {
    // 数据库连接工具类
    @Autowired
    private ConnectionUtils connectionUtils;

    @Pointcut("execution(* services.*.*(..))")
    private void transactionPointcut() {
    }

    /**
     * 开启事务
     */
    @Before("transactionPointcut()")
    public void beginTransaction() {
        try {
            System.out.println("开启事务");
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    @AfterReturning("transactionPointcut()")
    public void commit() {
        try {
            System.out.println("提交事务");
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    @AfterThrowing("transactionPointcut()")
    public void rollback() {
        try {
            System.out.println("回滚事务");
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    @After("transactionPointcut()")
    public void release() {
        try {
            System.out.println("释放连接");
            connectionUtils.getThreadConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        connectionUtils.removeConnection();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值