任务二:AOP

任务二:AOP

课程任务主要内容:

* 转账案例 
* Proxy优化转账案例 
* 初识AOP 
* 基于XML的AOP开发 
* 基于注解的AOP开发 
* AOP优化转账案例 

一 转账案例

需求

使用spring框架整合DBUtils技术,实现用户转账功能

1.1 基础功能

步骤分析

1. 创建java项目,导入坐标 
2. 编写Account实体类 
3. 编写AccountDao接口和实现类 
4. 编写AccountService接口和实现类 
5. 编写spring核心配置文件 
6. 编写测试代码 

1)创建java项目spring_transfer_deomo,导入坐标

pom.xml

<!--指定编码和版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>1.11</java.version>
        <maven.compiler.source>1.11</maven.compiler.source>
        <maven.compiler.target>1.11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.15</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2) 编写Account实体类

package com.myLagou.entity;

/**
 * @author zhy
 * @create 2022-08-13 21:15
 */
public class Account {
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

3)编写AccountDao接口和实现类

AccountDao接口

public interface AccountDao {
    //转出操作
    public void out(String outUser, Double money);

    //转入操作
    public void in(String inUser, Double money);
}

AccountDaoImpl实现类

package com.myLagou.dao.impl;

import com.myLagou.dao.AccountDao;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;

/**
 * @author zhy
 * @create 2022-08-13 21:20
 */
@Repository("accountDao")//生成该类的实例存到ioc容器中
public class AccountDaoImpl implements AccountDao {
    
    @Autowired
    private QueryRunner queryRunner;
    
    @Override
    public void out(String outUser, Double money) {
        //编写sql
        String sql = "update account set money = money - ? where name = ?";
        try {
            int update = queryRunner.update(sql, money, outUser);
            System.out.println("转出操作执行成功!" + update);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void in(String inUser, Double money) {
    String sql = "update account set money = money + ? where name = ?";
        try {
            int update = queryRunner.update(sql, money, inUser);
            System.out.println("转入操作执行成功!" + update);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

4)编写AccountService接口和实现类

AccountService接口

public interface AccountService {
    //转账方法
    public void transfer(String outUser, String inUser, Double money);
}

AccountServiceImpl实现类

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

    @Autowired
    private AccountDao accountDao;

    @Override
    public void transfer(String outUser, String inUser, Double money) {
        //转出操作,也就是给当前转户减少金额
        accountDao.out(outUser, money);
        
        //转入操作,也就是给一个账户增加金额
        accountDao.in(inUser,money);
    }
}

5)编写spring核心配置文件

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"
       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"
>
    <!--开启注解扫描组件-->
    <context:component-scan base-package="com.myLagou"></context:component-scan>

    <!--引入jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    
    <!--配置dataSource-->
    <!--配置数据源dataSource,传递给queryRunner-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>
    
    <!--配置queryRunner-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
</beans>

6)编写测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void transferTest(){
        accountService.transfer("jack", "杨洋", 100.0);
    }
}

7)问题分析

上面的代码事务在dao层,转出转入操作都是一个独立的事务,互不干扰,但实际开发,应该把业务逻辑控制在一个事务中,所以应该将事务挪到service层。当转出和转入操作在不同的事务中时,一旦在二者之间出现异常,那么就会造成一方数据改变,但另一方数据却没有改变的错误。

1.2 传统事务

步骤分析

1. 编写线程绑定工具类   作用:把要用到的connection连接对象与当前线程进行绑定,从而来保证在dao层调用事务方法时是同一个connection,即业务逻辑控制在一个事务中
2. 编写事务管理器 
3. 修改service层代码 
4. 修改dao层代码 

1)编写线程绑定工具类

ConnectionUtils工具类

/*连接工具类:从数据源中获取一个连接,并且将获得到的连接与线程进行绑定*/
@Component//生成该类的Bean对象保存到ioc容器中
public class ConnectionUtils {

    @Autowired
    private DataSource dataSource;//先获取数据源

    /*
    ThreadLocal类:线程内部的存储类,可以在指定的线程内部存储数据,就相当于一个容器,
    结构类似于map, key:ThreadLocal(当前线程)  value:任意类型的值
     */
    //threadLocal相当于一个容器,存放的就是connection
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /*获取当前线程上绑定的连接,如果获取到的连接为空,
    那么就需要从数据源中获取连接,并且放到ThreadLocal中(也就是将数据源绑定到当前线程上)*/
    public Connection getThreadConnection(){
        //1、先从ThreadLocal上获取连接
        Connection connection = threadLocal.get();
        
        //2、对获取的连接进行判断,看是否有connection
        if (connection == null){//连接为空
            //3、从数据源中获取连接,并将获得的连接存放到ThreadLocal中
            try {
                connection = dataSource.getConnection();
                //保存连接到ThreadLocal
                threadLocal.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return connection;
    }
    
     /*接触当前线程的连接绑定*/
    public void removeThreadConnection(){
        threadLocal.remove();
    }
}

2)编写事务管理器

TransactionManager事务管理器工具类

/*事务管理器工具类,包含的方法有:开启事务、提交事务、回滚事务、释放资源*/
    @Component
public class TransactionManager {
    //注入连接
    private ConnectionUtils connectionUtils;
    
    /*开启事务*/
    public void beginTransaction(){
        //获取connection对象
        Connection threadConnection = connectionUtils.getThreadConnection();
        try {
            //开启手动提交事务,也就是关闭自动提交事务
            threadConnection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /*提交事务*/
    public void commit(){
        Connection threadConnection = connectionUtils.getThreadConnection();
        try {
            threadConnection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    /*回滚事务*/
    public void rollback(){
        Connection threadConnection = connectionUtils.getThreadConnection();
        try {
            threadConnection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    /*释放资源*/
    public void release(){
        Connection threadConnection = connectionUtils.getThreadConnection();
        //将手动提交事务改为自动提交事务
        try {
            threadConnection.setAutoCommit(true);
            
            //将连接归还到连接池
//            threadConnection.close();
            connectionUtils.getThreadConnection().close();
            
            //解除线程绑定
            connectionUtils.removeThreadConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

3)修改service层代码

AccountServiceImpl实现类

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

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private TransactionManager transactionManager;

    @Override
    public void transfer(String outUser, String inUser, Double money) {
        //手动开启事务:调用事务管理类中的开启事务方法
        transactionManager.beginTransaction();

        try {
            //转出操作,也就是给当前转户减少金额
            accountDao.out(outUser, money);

            //转入操作,也就是给一个账户增加金额
            accountDao.in(inUser,money);

            //手动提交事务
            transactionManager.commit();
        } catch (Exception e) {
            e.printStackTrace();
            //手动回滚事务
            transactionManager.rollback();
        }finally {
            //手动释放资源
            transactionManager.release();
        }
    }
}

4)修改dao层代码

AccountDaoImpl实现类

@Repository("accountDao")//生成该类的实例存到ioc容器中
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private QueryRunner queryRunner;
    @Autowired
    private ConnectionUtils connectionUtils;

    @Override
    public void out(String outUser, Double money) {
        //编写sql
        String sql = "update account set money = money-? where name = ?";
        try {
            int update = queryRunner.update(connectionUtils.getThreadConnection(),sql, money, outUser);
            System.out.println("转出操作执行成功!" + update);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void in(String inUser, Double money) {
        String sql = "update account set money = money + ? where name = ?";
        try {
            int update = queryRunner.update(connectionUtils.getThreadConnection(),sql, money, inUser);
            System.out.println("转入操作执行成功!" + update);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

5)问题分析

上面代码,通过对业务层改造,已经可以实现事务控制了,但是由于我们添加了事务控制,也产生了一个新的问题: 业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了,违背了面向对象的开发思想。

Proxy优化转账案例

我们可以将业务代码和事务代码进行拆分,通过动态代理的方式,对业务方法进行事务的增强。这样就不会对业务层产生影响,解决了耦合性的问题啦!

常用的动态代理技术

JDK 代理 : 基于接口的动态代理技术·:利用拦截器(必须实现invocationHandler)加上反射机制生成一个代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理,从而实现方法增强

CGLIB代理:基于父类的动态代理技术:动态生成一个要代理的子类,子类重写要代理的类的所有不是final的方法。在子类中采用方法拦截技术拦截所有的父类方法的调用,顺势织入横切逻辑,对方法进行增强

在这里插入图片描述

2.1 JDK动态代理方式

2.2.1 Jdk工厂类

/*JDK动态代理工厂类*/
@Component
public class JDKProxyFactory {
    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionManager transactionManager;

    /*采用JDK动态代理技术生成目标类(被代理对象)的代理对象*/
    public AccountService createAccountServiceJDKProxy() {

        /*
        newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
         ClassLoader loader:类加载器,借助被代理对象获取到类加载器
         Class<?>[] interfaces:被代理类所需要实现的全部接口
         InvocationHandler h:当代理对象调用接口中的任意方法时,都会执行InvocationHandler接口中的invoke方法,所以可以在invoke方法中完成对代码的动态增强

         */
        AccountService accountServiceProxy = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {//匿名内部类
                    //重写invoke方法
                    @Override
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        /*
                        Object o:当前的代理对象引用
                        Method method:被调用的目标方法的引用
                        Object[] objects:被调用目标方法所用到的参数
                         */

                        try {
                            //手动开启事务:调用事务管理类中的开启事务方法
                            transactionManager.beginTransaction();

                            //借助反射,让被代理对象的原方法执行
                            method.invoke(accountService, objects);

                            //手动提交事务
                            transactionManager.commit();
                        } catch (Exception e) {
                            e.printStackTrace();
                            //手动回滚事务
                            transactionManager.rollback();
                        } finally {
                            //手动释放资源
                            transactionManager.release();
                        }

                        return null;
                    }
                });

        return accountServiceProxy;
    }
}

被代理类AccountServiceImpl

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

    @Autowired
    private AccountDao accountDao;
//    @Autowired
//    private TransactionManager transactionManager;

    @Override
    public void transfer(String outUser, String inUser, Double money) {
        System.out.println("transfer方法执行了");

        //转出操作,也就是给当前转户减少金额
        accountDao.out(outUser, money);
        //产生异常,测试事务回滚
        int i = 1/0;
        //转入操作,也就是给一个账户增加金额
        accountDao.in(inUser,money);

        /**
        //当使用了代理来优化代码时,在这个方法中就不需要执行事务操作了,事务的开启与提交等都由代理类来完成
        //手动开启事务:调用事务管理类中的开启事务方法
        transactionManager.beginTransaction();
        try {
            //转出操作,也就是给当前转户减少金额
            accountDao.out(outUser, money);
            //产生异常,测试事务回滚
            //int i = 1/0;
            //转入操作,也就是给一个账户增加金额
            accountDao.in(inUser,money);
            //手动提交事务
            transactionManager.commit();
        } catch (Exception e) {
            e.printStackTrace();
            //手动回滚事务
            transactionManager.rollback();
        }finally {
            //手动释放资源
            transactionManager.release();
        }*/
    }
}

测试

    /*测试jdk动态代理优化,减少业务层耦合*/
    @Test
    public void transferJDKProxyTest(){
        AccountService accountServiceJDKProxy = jdkProxyFactory.createAccountServiceJDKProxy();
        //当前返回的实际上是AccountService的一个代理对象proxy

        //代理对象proxy在调用接口中的任何方法时,都会执行底层的invoke方法
        accountServiceJDKProxy.transfer("jack", "杨洋", 100.0);
    }

2.2 CGLIB动态代理方式

Cglib工厂类

/*采用CGLIB动态代理来对目标类(AccountServiceImpl)进行方法的动态增强*/
@Component
public class CGLIBProxyFactory {
    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionManager transactionManager;

    public AccountService createCGlibProxy(){
        //编写CGlib对应的API来生成代理对象进行返回

            //参数1:目标类的字节码对象,
        // 参数2:动作类,当代理对象调用目标对象中的原方法时,会执行当前这个匿名内部类中的intercept方法
        AccountService accountServiceProxy = (AccountService) Enhancer.create(accountService.getClass(), new MethodInterceptor() {

            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        /*
                        Object o:当前的代理对象引用
                        Method method:被调用的目标方法的引用
                        Object[] objects:被调用目标方法所用到的参数
                        MethodProxy methodProxy:代理方法
                         */
                try {
                    //手动开启事务:调用事务管理类中的开启事务方法
                    transactionManager.beginTransaction();

                    //借助反射,让被代理对象的原方法执行
                    method.invoke(accountService, objects);

                    //手动提交事务
                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    //手动回滚事务
                    transactionManager.rollback();
                } finally {
                    //手动释放资源
                    transactionManager.release();
                }
                return null;
            }
        });
        return accountServiceProxy;
    }
}

测试

    /*测试CGlib动态代理优化,减少业务层耦合*/
    @Test
    public void transferCGlibProxyTest(){
        AccountService cGlibProxy = cglibProxyFactory.createCGlibProxy();
        //当前返回的实际上是AccountService的一个代理对象proxy

        //代理对象proxy在调用接口中的任何方法时,都会执行底层的invoke方法
        cGlibProxy.transfer("jack", "杨洋", 100.0);
    }

三 初识AOP

3.1 什么是AOP

AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程

AOP 是 OOP(面向对象编程) 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

这样做的好处是

  1. 在程序运行期间,在不修改源码的情况下对方法进行功能增强

  2. 逻辑清晰,开发核心业务的时候,不必关注增强业务的代码

  3. 减少重复代码,提高开发效率,便于后期维护

3.2 AOP底层实现

实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。

3.3 AOP相关术语

Spring 的 AOP 实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强

初体验

接口

public interface AccountService {
    //转账方法
    public void transfer(String outUser, String inUser, Double money);

    public void save();

    public void update();

    public void delete();

实现类

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Override
    public void transfer(String outUser, String inUser, Double money) {
        System.out.println("transfer方法执行了");

        //转出操作,也就是给当前转户减少金额
        accountDao.out(outUser, money);
        //产生异常,测试事务回滚
        //int i = 1/0;
        //转入操作,也就是给一个账户增加金额
        accountDao.in(inUser,money);
    }

    @Override
    public void save() {
        System.out.println("save方法");
    }

    @Override
    public void update() {
        System.out.println("update方法");
    }

    @Override
    public void delete() {
        System.out.println("delete方法");
    }
}

代理类

/*JDK动态代理工厂类*/
@Component
public class JDKProxyFactory {
    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionManager transactionManager;

    /*采用JDK动态代理技术生成目标类(被代理对象)的代理对象*/
    public AccountService createAccountServiceJDKProxy() {

        AccountService accountServiceProxy = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {//匿名内部类
                    //重写invoke方法
                    @Override
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                        try {
                            if (method.getName().equalsIgnoreCase("transfer")){
                                System.out.println("进行了前置增强");
                                //手动开启事务:调用事务管理类中的开启事务方法
                                transactionManager.beginTransaction();

                                //借助反射,让被代理对象的原方法执行
                                method.invoke(accountService, objects);

                                System.out.println("进行了后置增强");

                                //手动提交事务
                                transactionManager.commit();
                            }else {
                                method.invoke(accountService, objects);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            //手动回滚事务
                            transactionManager.rollback();
                        } finally {
                            //手动释放资源
                            transactionManager.release();
                        }

                        return null;
                    }
                });

        return accountServiceProxy;
    }
}

测试

    @Test
    public void transferJDKProxyTest(){
        AccountService accountServiceJDKProxy = jdkProxyFactory.createAccountServiceJDKProxy();
        //当前返回的实际上是AccountService的一个代理对象proxy

        //代理对象proxy在调用接口中的任何方法时,都会执行底层的invoke方法
        accountServiceJDKProxy.transfer("jack", "杨洋", 100.0);//进行了事务增强
        accountServiceJDKProxy.save();//只输出方法原本内容  save方法
        /*
        当在调用进行了事务增强的方法时才会输出增强的内容
        调用没有进行事务增强的方法时,只是输出方法原本有的内容
         */
    }

在正式讲解 AOP 的操作之前,我们必须理解 AOP 的相关术语,常用的术语如下:

  • Target(目标对象):代理的目标对象,

  • Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类

  • Joinpoint(连接点):所谓连接点是指那些可以被拦截到的点。在spring中,这些点指的是方法,因为 spring只支持方法类型的连接点

  • Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义 ,被代理类要被增强的方法

  • Advice(通知/ 增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知

    • 分类:前置通知、后置通知、异常通知、最终通知、环绕通知(环绕异常是spring提供的一种可以让我们通过代码的方式来手动控制的类型)
  • Aspect(切面):是切入点和通知(引介)的结合

  • Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织 入,而AspectJ采用编译期织入和类装载期织入

在这里插入图片描述

在这里插入图片描述

3.4 AOP开发明确事项

3.4.1 开发阶段(我们做的)

  1. 编写核心业务代码(目标类的目标方法) 切入点

  2. 把公用代码抽取出来,制作成通知(增强功能方法) 通知

  3. 在配置文件中,声明切入点与通知间的关系,即切面

3.4.2 运行阶段(Spring框架完成的)

Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。

3.4.3 底层代理实现

在 Spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。

  • 当bean实现接口时,会用JDK代理模式

  • 当bean没有实现接口,用cglib实现( 可以强制使用cglib(在spring配置中加入<aop:aspectj-autoproxy proxyt-target-class=”true”/>)

3.5 知识小结

  • aop:面向切面编程

  • aop底层实现:基于JDK的动态代理 和 基于Cglib的动态代理

  • aop的重点概念:

    • ​ Pointcut(切入点):真正被增强的方法
    • Advice(通知/ 增强):封装增强业务逻辑的方法
    • Aspect(切面):切点+通知
    • Weaving(织入):将切点与通知结合,产生代理对象的过程

四 基于XML的AOP开发

4.1 快速入门

步骤分析

1. 创建java项目,导入AOP相关坐标
2. 创建目标接口和目标实现类(定义切入点) 
3. 创建通知类及方法(定义通知) 
4. 将目标类和通知类对象创建权交给spring 
5. 在核心配置文件中配置织入关系,及切面
6. 编写测试代码

4.1.1 创建java项目spring_aop_xml,导入AOP相关坐标

pom.xml

 <!--指定编码和版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>1.11</java.version>
        <maven.compiler.source>1.11</maven.compiler.source>
        <maven.compiler.target>1.11</maven.compiler.target>
    </properties>

    <dependencies>
        <!--导入spring的context坐标,context依赖aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <!-- aspectj的织入(切点表达式需要用到该jar包) -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

        <!--spring整合junit-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

4.1.2 创建目标接口和目标实现类

AccountService接口

@Service
public interface AccountService {
    /*目标方法,也就是切入点,需要进行拦截增强的方法*/
    public void transfer();
}

AccountServiceImpl实现类

public class AccountServiceImpl implements AccountService {
    @Override
    /*目标方法,也就是切入点,需要进行拦截增强的方法*/
    public void transfer() {
        System.out.println("转账方法执行了!!!");
    }
}

4.1.3 创建通知类

MyAdvice通知类

/*通知类*/
public class MyAdvice {

    public void before(){
        System.out.println("前置通知执行了");
    }
      public void afterReturning(){
        System.out.println("后置通知执行了");
    }
}

4.1.4 将目标类和通知类对象创建权交给spring

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: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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
    <!--目标类交给ioc容器-->
    <bean id="accountService" class="com.myLagou.service.impl.AccountServiceImpl"></bean>

    <!--通知类交给ioc容器,也就是把通知类的实例对象保存到ioc容器中-->
    <bean id="myAdvice" class="com.myLagou.advice.MyAdvice"></bean>

</beans>

4.1.5 在核心配置文件中配置织入关系,及切面

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: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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
    <!--目标类交给ioc容器-->
    <bean id="accountService" class="com.myLagou.service.impl.AccountServiceImpl"></bean>

    <!--通知类交给ioc容器,也就是把通知类的实例对象保存到ioc容器中-->
    <bean id="myAdvice" class="com.myLagou.advice.MyAdvice"></bean>

    <!--AOP配置-->
    <aop:config>
        <!--配置切面:切入点+通知-->
        <aop:aspect ref="myAdvice">
            <!--ref="myAdvice":表示引入通知-->
            <!--配置前置通知    method="before":表示要用到通知类的哪个方法作为通知方法
               pointcut表示配置切入点              -->
     <aop:before method="before" pointcut="execution(public void com.myLagou.service.impl.AccountServiceImpl.transfer())"></aop:before>
            <!--这部分代码的作用:配置目标类的transfer方法执行时,使用myAdvice类中的before方法做一个前置增强-->

            <!--配置后置增强通知-->
            <aop:after-returning method="afterReturning" pointcut="execution(* com.myLagou.service.impl.AccountServiceImpl.*(..)))"></aop:after-returning>

        </aop:aspect>
    </aop:config>
</beans>

4.1.6 编写测试代码

AccountServiceTest测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer(){
        System.out.println("测试基于xml方式的aop开发");
        accountService.transfer();
    }
}

4.2 XML配置AOP详解

4.2.1 切点表达式

表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))

  • 访问修饰符可以省略

  • 返回值类型、包名、类名、方法名可以使用星号 * 代替,代表任意

    • 示例:execution(* *.*.*.*.*.*())
      
  • 包名与类名之间一个点 . 代表当前包下的类,两个点 … 表示当前包及其子包下的类

    • 示例:execution(* *..*.*())
      
  • 参数列表可以使用两个点 … 表示任意个数,任意类型的参数列表

    • 示例:execution(* *..*.*(..))
      

切点表达式抽取

当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替pointcut 属性来引用抽取后的切点表达式

在applicationContext.xml文件中配置AOP时,可以将重复的切点表达式提取出来为通用的

<!--AOP配置-->
    <aop:config>
        <!--抽取重复的切点表达式-->
        <aop:pointcut id="myPointCut" expression="execution(* com.myLagou.service.impl.AccountServiceImpl.*(..)))"/>
        
        <!--配置切面:切入点+通知-->
        <aop:aspect ref="myAdvice">
            <!--ref="myAdvice":表示引入通知-->
            <!--==切点表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))==-->
            <!--配置前置通知    method="before":表示要用到通知类的哪个方法作为通知方法
               pointcut表示配置切入点              -->
            <aop:before method="before" pointcut="execution(public void com.myLagou.service.impl.AccountServiceImpl.transfer())"></aop:before>
            <!--这部分代码的作用:配置目标类的transfer方法执行时,使用myAdvice类中的before方法做一个前置增强-->

            <!--配置后置增强通知-->
            <!--pointcut-ref="myPointCut":表示引入抽取的切点表达式-->
            <aop:after-returning method="afterReturning" pointcut-ref="myPointCut"></aop:after-returning>

        </aop:aspect>
    </aop:config>

4.2.2 通知类型

通知的配置语法:

<aop:通知类型 method=“通知类中方法名” pointcut=“切点表达式"></aop:通知类型>

名称标签说明
前置通知<aop:before>用于配置前置通知。指定增强的方法在切入点方法之前执行
后置通知<aop:afterReturning>用于配置后置通知。指定增强的方法在切入点方法之后执行
异常通知<aop:afterThrowing>用于配置异常通知。指定增强的方法出现异常后执行
最终通知<aop:after>用于配置最终通知。无论切入点方法执行时是否有异常,都会执行
环绕通知<aop:around>用于配置环绕通知。开发者可以手动控制增强代码在什么时候执行

注意:通常情况下,环绕通知都是独立使用的

测试环绕通知
/*通知类*/
public class MyAdvice {

    /*环绕通知,spring提供的一种可以让我们通过代码的方式来手动控制的类型*/
    /*ProceedingJoinPoint:正在执行的连接点,也就是切点*/
    public Object around(ProceedingJoinPoint joinPoint){

        Object proceed = null;
        try {
            System.out.println("前置通知执行了");
            //切点方法执行
             proceed = joinPoint.proceed();

            System.out.println("后置通知执行了");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("异常通知执行了");
        }finally {
            System.out.println("最终通知执行了");
        }
        return proceed;
    }
}
    <!--AOP配置-->
    <aop:config>
        <!--抽取重复的切点表达式-->
        <aop:pointcut id="myPointCut" expression="execution(* com.myLagou.service.impl.AccountServiceImpl.*(..)))"/>

        <!--配置切面:切入点+通知-->
        <aop:aspect ref="myAdvice">

            <!--配置环绕通知-->
            <aop:around method="around" pointcut-ref="myPointCut"></aop:around>


        </aop:aspect>
    </aop:config>
//测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer(){
        System.out.println("测试基于xml方式的aop开发");
        accountService.transfer();
    }
}

4.3 知识小结

* aop织入的配置 
	<aop:config> 
		<aop:aspect ref=“通知类”> 
			<aop:before method=“通知方法名称” pointcut=“切点表达式">
			</aop:before> 
		</aop:aspect> 
	</aop:config> 
	
* 通知的类型 
	前置通知、后置通知、异常通知、最终通知 环绕通知 
	
* 切点表达式 
	execution([修饰符] 返回值类型 包名.类名.方法名(参数))

五 基于注解的AOP开发

5.1 快速入门

步骤分析

1. 创建java项目,导入AOP相关坐标 
2. 创建目标接口和目标实现类(定义切入点) 
3. 创建通知类(定义通知) 
4. 将目标类和通知类对象创建权交给spring 
5. 在通知类中使用注解配置织入关系,升级为切面类 
6. 在配置文件中开启组件扫描和 AOP 的自动代理 
7. 编写测试代码 

5.1.1 创建java项目spring_aop_anno,导入AOP相关坐标

<!--指定编码和版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>1.11</java.version>
        <maven.compiler.source>1.11</maven.compiler.source>
        <maven.compiler.target>1.11</maven.compiler.target>
    </properties>

    <dependencies>
        <!--导入spring的context坐标,context依赖aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <!-- aspectj的织入(切点表达式需要用到该jar包) -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

        <!--spring整合junit-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

5.1.2 创建目标接口和目标实现类

接口AccountService

public interface AccountService {
    public void transfer();
}

实现类AccountServiceImpl


public class AccountServiceImpl implements AccountService {
    @Override
    public void transfer() {
        System.out.println("转账方法执行了!!!");
    }
}

5.1.3 创建通知类

通知类

/*通知类*/
public class myAdvice {
    @Before("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..))")
    public void before(){
        System.out.println("前置方法执行了!!!");
    }
}

5.1.4 将目标类和通知类对象创建权交给spring

//目标类
@Service
public class AccountServiceImpl implements AccountService {
    @Override
    public void transfer() {
        System.out.println("转账方法执行了!!!");
    }
}



/*通知类*/
    @Component
public class myAdvice {

    @Before("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..))")
    public void before(){
        System.out.println("前置方法执行了!!!");
    }
}

5.1.5 在通知类中使用注解配置织入关系,升级为切面类

/*通知类*/
    @Component
    @Aspect//使这个类成为切片类   在这个切片类中配置切入点和通知的关系
public class myAdvice {

    @Before("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..))")
    public void before(){
        System.out.println("前置方法执行了!!!");
    }
}

5.1.6 在配置文件中开启组件扫描和 AOP 的自动代理

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: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
">

    <!--开启ioc注解扫描组件-->
    <context:component-scan base-package="com.myLagou"></context:component-scan>

    <!--开启AOP自动代理    使通知类中的@Aspect注解生效 -->
    <!--spring会采用jdk动态代理完成织入增强,并生成代理-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <!--proxy-target-class="true":表示强制使用CGlib动态代理-->
<!--    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>-->
    
</beans>

5.1.7 编写测试代码

//测试类
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
        @Autowired
        private AccountService accountService;

    @Test
    public void testTransfer(){
        accountService.transfer();

    }
}

5.2 注解配置AOP详解

5.2.1 切点表达式的抽取

切点表达式的抽取

/*通知类*/
    @Component
    @Aspect//使这个类成为切片类   在这个切片类中配置切入点和通知的关系
public class myAdvice {

        //抽取公共的切点表达式
        @Pointcut("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..))")
        public void myPoint(){}

    @Before("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..))")
    public void before(){
        System.out.println("前置方法执行了!!!");
    }


    @AfterReturning("myAdvice.myPoint()")//引用公共的切点表达式
    public void afterReturning(){
        System.out.println("后置方法执行了!!!");
    }
}

5.2.2 通知类型

通知的配置语法:@通知注解(“切点表达式")

名称标签说明
前置通知@Before用于配置前置通知。指定增强的方法在切入点方法之前执行
后置通知@AfterReturning用于配置后置通知。指定增强的方法在切入点方法之后执行
异常通知@AfterThrowing用于配置异常通知。指定增强的方法出现异常后执行
最终通知@After用于配置最终通知。无论切入点方法执行时是否有异常,都会执行
环绕通知@Around用于配置环绕通知。开发者可以手动控制增强代码在什么时候执行

注意:

在使用注解配置通知时,当前四个通知组合在一起时,执行顺序如下:

@Before -> @After -> @AfterReturning(如果有异常:@AfterThrowing)

当使用注解配置通知的时候,使用环绕通知可以控制通知的执行顺序

package com.myLagou.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author zhy
 * @create 2022-08-14 23:14
 */
/*通知类*/
    @Component
    @Aspect//使这个类成为切片类   在这个切片类中配置切入点和通知的关系
public class myAdvice {

    //抽取公共的切点表达式
    @Pointcut("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..))")
    public void myPoint() {
    }

  /*  @Before("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..))")
    public void before() {
        System.out.println("前置通知方法执行了!!!");
    }


    @AfterReturning("myAdvice.myPoint()")//引用公共的切点表达式
    public void afterReturning() {
        System.out.println("后置通知方法执行了!!!");
    }

    @AfterThrowing("myAdvice.myPoint()")//引用公共的切点表达式
    public void afterThrowing() {
        System.out.println("异常通知方法执行了!!!");
    }

    @After("myAdvice.myPoint()")//引用公共的切点表达式
    public void after() {
        System.out.println("最终通知方法执行了!!!");
    }*/


    @Around("myAdvice.myPoint()")//引用公共的切点表达式
    public Object around(ProceedingJoinPoint pjp) {
        Object proceed =null;

        try {
            System.out.println("前置通知方法执行了!!!");
            //连接点对象调用proceed方法,使目标方法执行
             proceed = pjp.proceed();

            System.out.println("后置通知方法执行了!!!");

        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("异常通知方法执行了!!!");
        } finally {
            System.out.println("最终通知方法执行了!!!");
        }

        return proceed;
    }
}

5.2.3 纯注解配置

在项目中新建一个配置类,使用注解来加载,实现纯注解开发AOP

//配置类
@Configuration
@ComponentScan("com.myLagou")//开启注解扫描
@EnableAspectJAutoProxy//开启AOP自动代理 替代了标签<aop:aspectj-autoproxy>
public class SpringConfig {
}



//测试类
    @RunWith(SpringJUnit4ClassRunner.class)
//    @ContextConfiguration("classpath:applicationContext.xml")//使用核心配置文件
    @ContextConfiguration(classes = SpringConfig.class)//使用纯注解开启AOP
public class AccountServiceTest {
        @Autowired
        private AccountService accountService;

    @Test
    public void testTransfer(){
        accountService.transfer();
    }
}

5.3 知识小结

* 使用@Aspect注解,标注切面类

* 使用@Before等注解,标注通知方法

* 使用@Pointcut注解,抽取切点表达式

* 配置aop自动代理 <aop:aspectj-autoproxy/> 或 @EnableAspectJAutoProxy

AOP优化转账案例

依然使用前面的转账案例,将两个代理工厂对象直接删除!改为spring的aop思想来实现

6.1 xml配置实现

1)引入依赖

<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

2)配置文件

<?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.myLagou"></context:component-scan>

    <!--配置AOP-->
    <aop:config>
        <!--配置切点表达式-->
        <aop:pointcut id="myPointCut" expression="execution(* com.myLagou.service.impl.AccountServiceImpl.*(..)))"/>

        <!--配置切面-->
        <aop:aspect ref="transactionManager"><!--指明通知类-->
            <aop:before method="beginTransaction" pointcut-ref="myPointCut"></aop:before>
            <aop:after-returning method="commit" pointcut-ref="myPointCut"></aop:after-returning>
            <aop:after-throwing method="rollback" pointcut-ref="myPointCut"></aop:after-throwing>
            <aop:after method="release" pointcut-ref="myPointCut"></aop:after>
        </aop:aspect>

    </aop:config>

    <!--引入jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!--配置dataSource-->
    <!--配置数据源dataSource,传递给queryRunner-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>

    <!--配置queryRunner-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
</beans>

3)切点

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

    @Autowired
    private AccountDao accountDao;
//    @Autowired
//    private TransactionManager transactionManager;

    /*在使用AOP来完成事务增强的时候,此方法就是切入点*/
    @Override
    public void transfer(String outUser, String inUser, Double money) {
        System.out.println("transfer方法执行了");

        //转出操作,也就是给当前转户减少金额
        accountDao.out(outUser, money);
        //产生异常,测试事务回滚
        //int i = 1/0;
        //转入操作,也就是给一个账户增加金额
        accountDao.in(inUser,money);
    }
}

4)事务管理器(通知)

package com.myLagou.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author zhy
 * @create 2022-08-13 23:50
 */

/*事务管理器工具类,包含的方法有:开启事务、提交事务、回滚事务、释放资源*/

/*在使用AOP来完成事务增强的时候,此类就是通知类*/
    @Component
public class TransactionManager {
    //注入连接
    @Autowired
    private ConnectionUtils connectionUtils;

    /*开启事务*/
    public void beginTransaction(){
        //获取connection对象
        Connection threadConnection = connectionUtils.getThreadConnection();
        try {
            //开启手动提交事务,也就是关闭自动提交事务
            threadConnection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /*提交事务*/
    public void commit(){
        Connection threadConnection = connectionUtils.getThreadConnection();
        try {
            threadConnection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /*回滚事务*/
    public void rollback(){
        Connection threadConnection = connectionUtils.getThreadConnection();
        try {
            threadConnection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /*释放资源*/
    public void release(){
        Connection threadConnection = connectionUtils.getThreadConnection();
        //将手动提交事务改为自动提交事务
        try {
            threadConnection.setAutoCommit(true);
            connectionUtils.getThreadConnection().close();

            //解除线程绑定
            connectionUtils.removeThreadConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

6.2 注解配置实现

1)pom.xml配置文件

    <!--指定编码和版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>1.11</java.version>
        <maven.compiler.source>1.11</maven.compiler.source>
        <maven.compiler.target>1.11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.15</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.13</version>
    </dependency>
    </dependencies>

2)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.myLagou"></context:component-scan>

    <!--开启AOP自动代理-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    <!--引入jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!--配置dataSource-->
    <!--配置数据源dataSource,传递给queryRunner-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>

    <!--配置queryRunner-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
</beans>

3)事务管理器(通知)

package com.myLagou.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author zhy
 * @create 2022-08-13 23:50
 */

/*事务管理器工具类,包含的方法有:开启事务、提交事务、回滚事务、释放资源*/

/*在使用AOP来完成事务增强的时候,此类就是通知类*/
    @Component
    @Aspect//表明此类为切面类
public class TransactionManager {
    //注入连接
    @Autowired
    private ConnectionUtils connectionUtils;

    /*配置环绕通知*/
    @Around("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..)))")
    public Object around(ProceedingJoinPoint pjp) throws SQLException {
        Object proceed = null;
        try {
            //手动提交事务
            connectionUtils.getThreadConnection().setAutoCommit(false);
            //执行切入点方法
             proceed = pjp.proceed();
             //手动提交事务
            connectionUtils.getThreadConnection().commit();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            //异常回滚事务
            connectionUtils.getThreadConnection().rollback();

        }finally {
            //最终释放资源
            connectionUtils.getThreadConnection().setAutoCommit(true);//将1手动提交事务恢复为自动提交事务
            //将连接归还到连接池
            connectionUtils.getThreadConnection().close();

            //解除线程绑定
            connectionUtils.removeThreadConnection();
        }
        return proceed;
    }
}

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;
    @Autowired
    private JDKProxyFactory jdkProxyFactory;
    @Autowired
    private CGLIBProxyFactory cglibProxyFactory;

    @Test
    public void transferTest(){
        accountService.transfer("jack", "杨洋", 100.0);
    }

}

an>






**3)事务管理器(通知)**

```java
package com.myLagou.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author zhy
 * @create 2022-08-13 23:50
 */

/*事务管理器工具类,包含的方法有:开启事务、提交事务、回滚事务、释放资源*/

/*在使用AOP来完成事务增强的时候,此类就是通知类*/
    @Component
    @Aspect//表明此类为切面类
public class TransactionManager {
    //注入连接
    @Autowired
    private ConnectionUtils connectionUtils;

    /*配置环绕通知*/
    @Around("execution(* com.myLagou.service.impl.AccountServiceImpl.*(..)))")
    public Object around(ProceedingJoinPoint pjp) throws SQLException {
        Object proceed = null;
        try {
            //手动提交事务
            connectionUtils.getThreadConnection().setAutoCommit(false);
            //执行切入点方法
             proceed = pjp.proceed();
             //手动提交事务
            connectionUtils.getThreadConnection().commit();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            //异常回滚事务
            connectionUtils.getThreadConnection().rollback();

        }finally {
            //最终释放资源
            connectionUtils.getThreadConnection().setAutoCommit(true);//将1手动提交事务恢复为自动提交事务
            //将连接归还到连接池
            connectionUtils.getThreadConnection().close();

            //解除线程绑定
            connectionUtils.removeThreadConnection();
        }
        return proceed;
    }
}

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;
    @Autowired
    private JDKProxyFactory jdkProxyFactory;
    @Autowired
    private CGLIBProxyFactory cglibProxyFactory;

    @Test
    public void transferTest(){
        accountService.transfer("jack", "杨洋", 100.0);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值