spring框架学习笔记03(AOP的引出)

01,AOP 的相关概念

1.1,AOP概述

1.1.1,什么是AOP

  • AOP: 全称是 Aspect Oriented Programming 即: 面向切面编程
  • 简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。

1.1.2,AOP的作用及优势

  • 作用:
    在程序运行期间,不修改源码对已有方法进行增强。
  • 优势:
    减少重复代码
    提高开发效率
    维护方便

1.1.3,AOP的实现方式

  • 使用动态代理技术

1.2,AOP的引出(应用)

  • 使用对账户的增删改查,一步一步的引出AOP
  • 数据库还是用笔记(01)里面的mySpring数据库,account表

1.2.1,环境搭建

在这里插入图片描述

1.2.1.1,创建一个Maven工程(spring)
  • 导入坐标
 <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</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>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
1.2.1.2,创建IAccountDao接口和AccountDaoImpl_old.java实现类
  • IAccountDao
/**
 * 账户的持久层接口
 */
public interface IAccountDao {

    /**
     * 查询所有
     */
    List<Account> findAllAccount();

    /**
     * 更新账户
     */
     void updateAccount(Account account);

    /**
     * 根据名称查询账户
     *  如果有唯一的一个结果就返回,如果没有结果就返回null
     *  如果结果集超过一个就抛异常
     */
    Account findAccountByName(String accountName);
}
  • AccountDaoImpl_old.java
public class AccountDaoImpl_old implements IAccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    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);
        }
    }

    @Override
    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);
        }
    }
}
1.2.1.3,创建IAccountService接口和AccountServiceImplImpl_old.java实现类
  • IAccountService
/**
 * 账户的业务层接口
 */
public interface IAccountService {

    /**
     * 查询所有
     */
    List<Account> findAllAccount();
    /**
     * 更新
     */
    void updateAccount(Account account);
    /**
     * 转账
     * @param sourceName        转出账户名称
     * @param targetName        转入账户名称
     * @param money             转账金额
     */
    void transfer(String sourceName, String targetName, Float money);
}
  • AccountServiceImpl_old.java
/**
 * 账户的业务层实现类
 *
 * 事务控制应该都是在业务层
 */
public class AccountServiceImpl_old implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
       return accountDao.findAllAccount();
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
        //2.1根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        System.out.println("转出账户转账之前剩余的金额"+source.getMoney());
        //2.2根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        System.out.println("转入账户转账之前剩余的金额"+target.getMoney());
        //2.3转出账户减钱
        source.setMoney(source.getMoney()-money);
        //2.4转入账户加钱
        target.setMoney(target.getMoney()+money);
        //2.5更新转出账户
        accountDao.updateAccount(source);
        System.out.println("转入账户转账之后剩余的金额"+target.getMoney());

        //int i=1/0;//此处设置一个异常,实现一个减钱,另外一个拿不到钱

        //2.6更新转入账户
        accountDao.updateAccount(target);
        System.out.println("转出账户转账之后剩余的金额"+source.getMoney());
    }
}
2.4 ,实体类Account.java
  • 实体类属性为:
private Integer id;
private String name;
private Float money;
2.5,在Resource文件加下创建配置文件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="accountService" class="com.aismall.service.impl.AccountServiceImpl_old">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.aismall.dao.impl.AccountDaoImpl_old">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>

    </bean>
    <!--配置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/mySpring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="12345678"></property>
    </bean>
</beans>
2.6,创建测试类AccountTest.java
/**
 * 使用Junit单元测试:测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private  IAccountService as;

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

1.2.2,案例中的问题

  • 问题就是:
    事务被自动控制了。换言之,我们使用了 connection 对象的 setAutoCommit(true)
  • 此方式控制事务,如果我们每次都执行一条 sql 语句,没有问题,但是如果业务方法一次要执行多条 sql语句,这种方式就无法实现功能了。
  • 例如:在上面的AccountServiceImpl_old.java类中,如果把2.5和2.6中间的那句i=1/0 打开就会出现问题,当一个商户转账之后,事务就被提交,转账操作完成,另外一个用户在接收之前,程序出现异常,接收失败,但是转账用户的金额也没有加回来,这不满足事务的一致性

1.2.3,问题的解决

  • 解决办法:
    让业务层来控制事务的提交和回滚
  • 在上面的代码中进行改写
    在这里插入图片描述
1.2.3.1,AccountDaoImpl_new.java
**
 * 账户的持久层实现类
 */

public class AccountDaoImpl_new implements IAccountDao {
        private QueryRunner runner;
        private ConnectionUtils connectionUtils;
        public void setRunner(QueryRunner runner) {
            this.runner = runner;
        }
        public void setConnectionUtils(ConnectionUtils connectionUtils) {
            this.connectionUtils = connectionUtils;
        }
        @Override
        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);
            }
        }

        @Override
        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);
            }
        }

        @Override
        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);
            }
        }
}
1.2.3.2,AccountServiceImpl_new.java
/**
 * 账户的业务层实现类
 *
 * 事务控制应该都是在业务层
 */
public class AccountServiceImpl_new implements IAccountService {

    private IAccountDao accountDao;
    private TransactionManager txManager;

    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            List<Account> accounts = accountDao.findAllAccount();
            //3.提交事务
            txManager.commit();
            //4.返回结果
            return accounts;
        }catch (Exception e){
            //5.回滚操作
            txManager.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.释放连接
            txManager.release();
        }

    }

    @Override
    public void updateAccount(Account account) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            accountDao.updateAccount(account);
            //3.提交事务
            txManager.commit();
        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
        }finally {
            //5.释放连接
            txManager.release();
        }

    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        try {
            //1.开启事务
            txManager.beginTransaction();
            //2.执行操作
            //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);
            System.out.println(source.getMoney());
            //int i=1/0;

            //2.6更新转入账户
            accountDao.updateAccount(target);
            System.out.println(target.getMoney());
            //3.提交事务
            txManager.commit();
            System.out.println("转账结束");
        }catch (Exception e){
            //4.回滚操作
            txManager.rollback();
            e.printStackTrace();
        }finally {
            //5.释放连接
            txManager.release();
        }
    }
}
1.2.3.3,util包中的两个工具类(重点)
  • TransactionManager.java
/**
 * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
 */
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();
    }
}

  • ConnectionUtils.java
/**
 * 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
 */
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();
        }
    }
}
1.2.3.4,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="accountService" class="com.aismall.service.impl.AccountServiceImpl_new">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
        <!--注入TransactionManager-->
        <property name="txManager" ref="transactionManager" ></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.aismall.dao.impl.AccountDaoImpl_new">
        <!-- 注入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/mySpring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="12345678"></property>
    </bean>

    <!--配置ConnectionUtils-->
    <bean id="connectionUtils" class="com.aismall.utils.ConnectionUtils" >
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置TransactionManager-->
    <bean id="transactionManager" class="com.aismall.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>
</beans>

1.2.4,新的问题

  • 通过对业务层改造,已经可以实现事务控制了,但是由于我们添加了事务控制,也产生了一个新的问题
  • 新的问题:
    业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了。如果我们此时提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码,况且这还只是一个业务层实现类,而实际的项目中这种业务层实现类可能有十几个甚至几十个。

1.2.5,新的问题解决办法

使用动态代理技术

  • 我们继续在之前的工程中进行改造
    在这里插入图片描述
1.2.5.1,在factory包中添加代理类BeanFactory
    /**
     * 用于创建Service的代理对象的工厂
     */
    public class BeanFactory {
        private IAccountService accountService;

        private TransactionManager txManager;

        public void setTxManager(TransactionManager txManager) {
            this.txManager = txManager;
        }
        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();
                            }
                        }
                    });
        }
    }
1.2.5.2,修改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.aismall.factory.BeanFactory">
        <!-- 注入service -->
        <property name="accountService" ref="accountService"></property>
        <!-- 注入事务管理器 -->
        <property name="txManager" ref="transactionManager"></property>
    </bean>

     <!-- 配置Service -->
    <bean id="accountService" class="com.aismall.service.impl.AccountServiceImpl_old">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.aismall.dao.impl.AccountDaoImpl_new">
        <!-- 注入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/mySpring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="12345678"></property>
    </bean>

    <!--配置ConnectionUtils-->
    <bean id="connectionUtils" class="com.aismall.utils.ConnectionUtils" >
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置TransactionManager-->
    <bean id="transactionManager" class="com.aismall.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>
</beans>
1.2.5.3,修改测试类
/**
 * 使用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);
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_45583303/article/details/106578205