SpringAOP

代理模式

什么是代理模式
这里提到了动态代理的概念,首先解释一下代理模式,代理模式是给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用

通俗来说就是委托人将整栋楼的空房间委托给代理商管理,代理商在不改变房屋架构的基础上二次装修,打造为青年公寓出租给有租房需求的客户

空房间就是原代码,二次装修就是给源代码统一添加功能,租房动作就是对源代码的引用

代理模式的意义
中间隔离作用:在一些情况下,一个客户类不想或者不能直接引用一个委托对象,而代理类对象可以在客户类和委托对象之间起媒介作用,其特征是代理类和委托类实现相同的接口
增加功能:给代理类增加额外的功能可以用来扩展委托类的功能,这样做只需要修改代理类而不需要再修改委托类
委托类和代理类的功能
委托类实现真正的业务功能
代理类
负责为委托类预处理消息、过滤消息、把消息转发给委托类,以及事后对返回结果的处理等
代理类本身并不真正实现服务,而是同过调用委托类的相关方法,来提供特定的服务
例如将项目加入缓存、日志这些功能就可以使用代理类来完成,没必要打开已经封装好的委托类
静态代理 & 动态代理
代理模式可以分为静态代理和动态代理:

静态代理
静态代理是由程序员创建或特定工具自动生成源代码,在程序运行之前,代理类就已经编译生成了.class文件。

静态代理的优点是可以在符合开闭原则的情况下对目标对象进行功能扩展,缺点则是开发人员需要为每一个服务都得创建代理类,工作量太大,不易管理。同时接口一旦发生改变,代理类也得相应修改

动态代理
动态代理是在程序运行时通过反射机制动态创建的,随用随加载。动态代理常用的有基于接口和基于子类两种方式

基于接口的动态代理指的是由JDK官方提供的Proxy类,要求被代理类最少实现一个接口,这种方式大大减少了开发人员的开发任务,减少了对业务接口的依赖,降低了耦合度,缺点就是注定有一个共同的父类叫Proxy,Java的继承机制注定了这些动态代理类们无法实现对class的动态代理,原因是多继承在Java中本质上就行不通

基于子类的动态代理指的是由第三方提供的CGLib,CGLib采用了非常底层的字节码技术,其原理是通过字节码技术为一个类创建子类,并在子类中采用方法拦截的技术拦截所有父类方法的调用,顺势织入横切逻辑。但因为采用的是继承,所以要求被代理类不能用final修饰,即不能是最终类

简单转账功能

我们新建Maven项目名为“spring-aop“,设置好Maven版本、配置文件以及Maven仓库

准备数据

# 删除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);

导包
1.导入Spring基础包

2.导入操作数据库、连接数据库、测试需要的包

<!-- 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="root"></property>
</bean>

代码编写
数据库连接工具类:ConnectionUtils.java

package utils;

@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模块实体类:Account.java

package entity;

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

Account模块Dao层:AccountDao.java

package dao;

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

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

Account模块Dao层实现类:AccountDaoImpl.java

package dao.impl;

@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层:AccountService.java

package services;

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

Account模块Service层实现类:AccountServiceImpl.java

package services.impl;

@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模块测试类:AccountTest.java

@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

此工具类主要作用是对数据库连接实现事务的开启,提交以及回滚

至于何时开启、提交、回滚事务,根据业务场景需要调用该类的方法即可

package transaction;

@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

此类的核心代码是getAccountService方法,该方法返回代理业务类示例

在代理对象的invoke方法内部,实现对原始被代理对象的增强

package utils;

@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")

执行结果
首先将数据库中两账户余额都改为1000

update account set money = 1000;

引入AOP(XML)

相关概念
使用Spring的AOP替代代理类。先回顾下AOP的概念

AOP是一种编程设计模式,是一种编程技术,使用AOP后通过修改配置即可实现增加或者去除某些附加功能

学习AOP中的常用术语:

Join point(连接点)
所谓连接点是指那些可以被拦截到的点

在Spring中这些点指的是方法,可以看作正在访问的,或者等待访问的那些需要被增强功能的方法

Spring只支持方法类型的连接点

Pointcut(切入点)
切入点是一个规则,定义了我们要对哪些Joinpoint进行拦截

因为在一个程序中会存在很多的类,每个类又存在很多的方法,Pointcut来标记哪些方法会应用AOP对该方法做功能增强

Advice(通知)
所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。也就是对方法做的增强功能。通知分为如下几类:

前置通知:在连接点之前运行的通知类型,它不会阻止流程进行到连接点,只是在到达连接点之前运行该通知内的行为

后置通知:在连接点正常完成后要运行的通知,正常的连接点逻辑执行完,会运行该通知

最终通知:无论连接点执行后的结果如何,正常还是异常,都会执行的通知

异常通知:如果连接点执行因抛出异常而退出,则执行此通知

环绕通知:环绕通知可以在方法调用之前和之后执行自定义行为

Target(目标)
Target指的是代理的目标对象,更通俗的解释就是:AOP对连接点方法做增强,底层是代理模式生成连接点所在类的代理对象,那么连接点所在的类,就是被代理的类称呼为Target

Aspect(切面)
切面本质是一个类,只不过是个功能类,作为整合AOP的切入点和通知。

一般来讲,需要在Spring的配置文件中配置,或者通过注解来配置

Weaving(织入)
织入是一种动作的描述,在程序运行时将增强的功能代码也就是通知,根据通知的类型(前缀后缀等…)放到对应的位置,生成代理对象

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

代码实现
在执行原始业务类前对方法增强也就是SpringAOP中所谓的前置通知,对原始业务类中的方法执行之后的增强行为就是后置通知

而一旦出现异常,那么所做的动作就是异常通知。本案例使用几种通知,来实现事务的控制。

删除事务代理工具类:TransactionProxyUtils.java

导入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>

修改测试类代码

RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")public class AccountTest {
Autowired
private AccountService accountService;
@Test
public void testTransfer() {
accountService.transfer( sourceAccount:"622200001",targetAccount:"622200002",money: 100);
}

XML改注解(AOP)

使用注解介绍
@Aspect
此注解用于表明某个类为切面类,而切面类的作用我们之前也解释过,用于整合切入点和通知

@Pointcut
此注解用于声明一个切入点,表明哪些类的哪些方法需要被增强

@Before 前置通知
在连接点之前运行的通知类型,它不会阻止流程进行到连接点,只是在到达连接点之前运行该通知内的行为

@AfterReturning 后置通知
在连接点正常完成后要运行的通知,正常的连接点逻辑执行完,会运行该通知

@After 最终通知
无论连接点执行后的结果如何,正常还是异常,都会执行的通知

@AfterThrowing 异常通知
如果连接点执行因抛出异常而退出,则执行此通知

代码实现
删除XML中的AOPXML配置并注解代理模式

<!-- 注解  开启代理模式 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

注释事务管理器类:TransactionManager.java

package transaction;

@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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值