Spring AOP ~ 从入门到入坑。

本文深入探讨Spring AOP原理及实战应用,从事务控制引入,详细解析动态代理机制,包括基于接口和基于子类的动态代理。阐述AOP术语如连接点、切入点、通知等,并演示如何使用Spring AOP进行事务管理,涵盖XML配置、注解驱动等多种方式。

Spring AOP ~ 从入门到入坑。



从事务引入。

转账操作。

在这里插入图片描述

没加事务控制的情况。

package com.geek.service.impl;

import com.geek.dao.IAccountDao;
import com.geek.domain.Account;
import com.geek.service.IAccountService;

import java.util.List;

/**
 * 账户的业务层实现类。
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

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

    /**
     * 转账操作。
     *
     * @param sourceName
     * @param targetName
     * @param money
     */
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        // 根据名称查询转出账户。
        Account source = accountDao.findByName(sourceName);
        // 根据名称查询转入账户。
        Account target = accountDao.findByName(targetName);
        // 转出账户减钱。
        source.setMoney(source.getMoney() - money);
        // 转入账户加钱。
        target.setMoney(target.getMoney() - money);
        // 更新转出账户。
        accountDao.updateAccount(source);

        int a = 1 / 0;

        // 更新转入账户。
        accountDao.updateAccount(target);
    }

    /**
     * 查找全部。
     *
     * @return
     */
    @Override
    public List<Account> FindAllAccount() {
        return accountDao.FindAllAccount();
    }

    /**
     * 根据 id 查找一个。
     *
     * @param accountId
     * @return
     */
    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    /**
     * 保存。
     *
     * @param account
     */
    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    /**
     * 修改。
     *
     * @param account
     */
    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    /**
     * 删除。
     *
     * @param accountId
     */
    @Override
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }

}



手动实现 ThreadLocal 线程池、连接池。

package com.geek.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 连接工具类。用于从数据库中获取一个连接,并且实现和线程的绑定。
 */
public class ConnectionUtils {

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 获取当前线程上的连接。
     *
     * @return
     */
    public Connection getThreadConnection() {

        try {
            // 先从 ThreadLocal 中获取。
            Connection connection = threadLocal.get();
            // 判断当前线程上是否有连接。
            if (connection == null) {
                // 从数据源中获取一个连接,并且写入 ThreadLocal 中。
                connection = dataSource.getConnection();

                threadLocal.set(connection);
            }
            // 返回当前线程的上的连接。
            return connection;
        } catch (SQLException e) {
//            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 把连接和线程解绑。
     */
    public void removeConnection() {
        threadLocal.remove();
    }

}

package com.geek.utils;

import java.sql.SQLException;

/**
 * 和事务管理相关的工具类。
 * 开启事务、提交事务、回滚事务和释放连接。
 */
public class TransactinManager {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

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

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

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

    /**
     * 释放连接。
     */
    public void releaseTransaction() {
        try {
            connectionUtils.getThreadConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 把连接和线程解绑。
     */
    public void removeConnection() {
        try {
            connectionUtils.getThreadConnection().close();
            connectionUtils.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}



连接池的好处。

把消耗时间获取 / 创建连接的过程放在加载应用(一开始),启动 Tomcat,加载应用就创建连接,在后续项目运行阶段不再找数据库获取连接,提升使用 Connection 的效率。

服务器也有“池”的技术——线程池。Tomcat 启动时会初始化一堆线程放入容器中,每次使用直接从容器中拿线程直接使用。
线程池中的连接调用 close(); 方法并不是关闭连接,而是还回连接池中。(线程中绑定了一个连接)。我们把连接关闭,把线程还回线程池中时,线程上还是有连接的,只不过是关闭的连接。下一次获取这个线程,要判断此线程中是否有连接时,if (connection == null) {} ——> false。但这个连接是 closed。

dao 层加入事务控制(手动版)。

package com.geek.service.impl;

import com.geek.dao.IAccountDao;
import com.geek.domain.Account;
import com.geek.service.IAccountService;
import com.geek.utils.TransactinManager;

import java.util.List;

/**
 * 账户的业务层实现类。
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    private TransactinManager transactinManager;

    public void setTransactinManager(TransactinManager transactinManager) {
        this.transactinManager = transactinManager;
    }

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

    /**
     * 转账操作。
     *
     * @param sourceName
     * @param targetName
     * @param money
     */
    @Override
    public void transfer(String sourceName, String targetName, Float money) {

        try {
            // 开启事务。
            transactinManager.beginTransaction();
            // 执行操作。

            // 根据名称查询转出账户。
            Account source = accountDao.findByName(sourceName);
            // 根据名称查询转入账户。
            Account target = accountDao.findByName(targetName);
            // 转出账户减钱。
            source.setMoney(source.getMoney() - money);
            // 转入账户加钱。
            target.setMoney(target.getMoney() - money);
            // 更新转出账户。
            accountDao.updateAccount(source);

            int a = 1 / 0;

            // 更新转入账户。
            accountDao.updateAccount(target);

            // 提交事务。
            transactinManager.commitTransaction();

        } catch (Exception e) {
            // 回滚操作。
            transactinManager.rollbackTransaction();
        } finally {
            // 释放连接。
            transactinManager.release();
        }
    }

    /**
     * 查找全部。
     *
     * @return
     */
    @Override
    public List<Account> FindAllAccount() {
        try {
            // 开启事务。
            transactinManager.beginTransaction();
            // 执行操作。
            List<Account> accountList = accountDao.FindAllAccount();
            // 提交事务。
            transactinManager.commitTransaction();
            // 返回结果。
            return accountList;
        } catch (Exception e) {
            // 回滚操作。
            transactinManager.rollbackTransaction();
            throw new RuntimeException(e);
        } finally {
            // 释放连接。
            transactinManager.release();
        }
    }

    /**
     * 根据 id 查找一个。
     *
     * @param accountId
     * @return
     */
    @Override
    public Account findAccountById(Integer accountId) {
        try {
            // 开启事务。
            transactinManager.beginTransaction();
            // 执行操作。
            Account account = accountDao.findAccountById(accountId);
            // 提交事务。
            transactinManager.commitTransaction();
            // 返回结果。
            return account;
        } catch (Exception e) {
            // 回滚操作。
            transactinManager.rollbackTransaction();
            throw new RuntimeException(e);
        } finally {
            // 释放连接。
            transactinManager.release();
        }
    }

    /**
     * 保存。
     *
     * @param account
     */
    @Override
    public void saveAccount(Account account) {
        try {
            // 开启事务。
            transactinManager.beginTransaction();
            // 执行操作。
            accountDao.saveAccount(account);
            // 提交事务。
            transactinManager.commitTransaction();
        } catch (Exception e) {
            // 回滚操作。
            transactinManager.rollbackTransaction();
        } finally {
            // 释放连接。
            transactinManager.release();
        }
    }

    /**
     * 修改。
     *
     * @param account
     */
    @Override
    public void updateAccount(Account account) {
        try {
            // 开启事务。
            transactinManager.beginTransaction();
            // 执行操作。
            accountDao.updateAccount(account);
            // 提交事务。
            transactinManager.commitTransaction();
        } catch (Exception e) {
            // 回滚操作。
            transactinManager.rollbackTransaction();
        } finally {
            // 释放连接。
            transactinManager.release();
        }
    }

    /**
     * 删除。
     *
     * @param accountId
     */
    @Override
    public void deleteAccount(Integer accountId) {
        try {
            // 开启事务。
            transactinManager.beginTransaction();
            // 执行操作。
            accountDao.deleteAccount(accountId);
            // 提交事务。
            transactinManager.commitTransaction();
        } catch (Exception e) {
            // 回滚操作。
            transactinManager.rollbackTransaction();
        } finally {
            // 释放连接。
            transactinManager.release();
        }
    }

}

这时不再希望注入 dataSource。

    <!-- 配置 QueryRunner 对象。-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"
          scope="prototype"><!-- prototype,每来一个连接创建一个对象,线程安全。-->
        <!-- 注入数据源。-->
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>

dao。


    private ConnectionUtils connectionUtils;

    // 让 Spring 注入。
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

并且每个 queryRunner 方法指定参数:连接。

在这里插入图片描述

package com.geek.dao.impl;

import com.geek.dao.IAccountDao;
import com.geek.domain.Account;
import com.geek.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 账户的持久层实现类。
 */
public class AccountDaoImpl implements IAccountDao {

    private QueryRunner queryRunner;

    private ConnectionUtils connectionUtils;

    // 让 Spring 注入。
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    /**
     * 根据名称查询账户。
     *
     * @param name
     * @return 如果有唯一结果就返回。如果没有结果返回 null。
     * 如果结果超过一个,就抛异常。
     */
    @Override
    public Account findByName(String name) {
        try {
//            List<Account> accountList = queryRunner.query("select * from account where name = ?", new BeanListHandler<>(Account.class), name);
            List<Account> accountList = queryRunner.query(connectionUtils.getThreadConnection(), "select * from account where name = ?", new BeanListHandler<>(Account.class), name);
            if (accountList == null || accountList.size() == 0) {
                return null;
            }
            return accountList.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Account> FindAllAccount() {
        try {
            return queryRunner.query(connectionUtils.getThreadConnection(), "select * from account", new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
//            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            return queryRunner.query(connectionUtils.getThreadConnection(), "select * from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
        } catch (SQLException e) {
//            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            queryRunner.update(connectionUtils.getThreadConnection(), "insert into account(name, money) values (?, ?)", account.getName(), account.getMoney());
        } catch (SQLException e) {
//            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            queryRunner.update(connectionUtils.getThreadConnection(), "update account set name = ?, money= ? where id = ?", account.getName(), account.getMoney(), account.getId());
        } catch (SQLException e) {
//            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try {
            queryRunner.update(connectionUtils.getThreadConnection(), "delete from account where id = ?", accountId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

重新配置注入。

<?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.geek.service.impl.AccountServiceImpl">
        <!-- 注入 dao。-->
        <property name="accountDao" ref="accountDao"/>
        <!-- 注入事务管理器。-->
        <property name="transactionManager" ref="txManager"/>
    </bean>

    <!-- 配置 dao 对象。-->
    <bean id="accountDao" class="com.geek.dao.impl.AccountDaoImpl">
        <!-- 注入 QueryRunner。-->
        <property name="queryRunner" ref="queryRunner"/>

        <!-- 注入 ConnectionUtils。-->
        <property name="connectionUtils" ref="connectionUtils"/>
    </bean>

    <!--    &lt;!&ndash; 配置 QueryRunner 对象。&ndash;&gt;
        <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"
              scope="prototype">&lt;!&ndash; prototype,每来一个连接创建一个对象,线程安全。&ndash;&gt;
            &lt;!&ndash; 注入数据源。&ndash;&gt;
            <constructor-arg name="ds" ref="dataSource"/>
        </bean>-->

    <!-- 配置 QueryRunner 对象。-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"
          scope="prototype"><!-- prototype,每来一个连接创建一个对象,线程安全。-->
    </bean>

    <!-- 配置数据源对象。-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 连接数据库的必备信息。-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://192.168.223.128:3306/geek_spring_dbutils"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>


    <!-- 配置 Connection 的工具类。-->
    <bean id="connectionUtils" class="com.geek.utils.ConnectionUtils">
        <!-- 注入数据源。-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置业务层的管理器。-->
    <bean id="txManager" class="com.geek.utils.TransactionManager">
        <!-- 注入 ConnectionUtils。-->
        <property name="connectionUtils" ref="connectionUtils"/>
    </bean>

</beans>

事务控制住了。

但配置相当麻烦。

Spring AOP 该出场了。






AOP~动态代理。

动态代理。

从买电脑引入。

在这里插入图片描述

最开始直接从生产厂家购买。

-~ ~ ~ ↓ ↓ ↓ ~ ~ ~ 生产厂家生产的电脑太多,库房存不下。

生产厂家自己的销售和售后。

-~ ~ ~ ↓ ↓ ↓ ~ ~ ~ 要养活销售部和售后部,成本高。

代理商 / 经销商。



Java 动态代理机制。

生产者。

package com.geek.proxy;

public interface IProducer {

    /**
     * 销售。
     *
     * @param money
     */
    void saleProduct(float money);

    /**
     * 售后。
     *
     * @param money
     */
    void afterMarket(float money);

}

package com.geek.proxy;

/**
 * 生产者。
 */
public class Producer implements IProducer {

    /**
     * 销售。
     *
     * @param money
     */
    public void saleProduct(float money) {
        System.out.println("销售产品,并拿到钱:" - money);
    }

    /**
     * 售后。
     *
     * @param money
     */
    public void afterMarket(float money) {
        System.out.println("提供售后服务,并拿到钱:" - money);
    }

}

消费者。

package com.geek.proxy;

/**
 * 模拟一个消费者。
 */
public class Client {

    public static void main(String[] args) {
        Producer producer = new Producer();

        producer.saleProduct(10000F);
    }

}



动态代理。
  • 特点:字节码随用随创建,随用随加载。

  • 作用:不修改源码的基础上对方法增强。

  • 分类。

基于接口的动态代理。
基于子类的动态代理。



基于接口的动态代理。
  • 涉及的类:Proxy。

  • 提供者:JDK 官方。

  • 如何创建代理对象。

使用 Proxy 类中的 newProxyInstance(); 方法。

  • 创建代理对象的要求。

被代理类至少实现一个接口,如果没有则不能使用。

  • newInstance() 方法的参数。
  • loader: ClassLoader ——> 类加载器。
    ~ 用于加载代理对象的字节码。和被代理对象使用相同的类加载器。(固定写法。.getClass().getClassLoader())。

  • interfaces: Class<?>[]
    ~ 用于让代理对象和被代理对象有相同的方法。(有相同的方法:实现同一接口)。(固定写法。.getClass().getInterfaces())。

  • h: InvocationHandler
    ~ 让我们写:如何代理。(用于提供增强的方法)。
    一般写一个该接口的实现类(一般是匿名内部类,但不是必须的)。此接口的实现类是谁用谁写。

package com.geek.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 模拟一个消费者。
 */
public class Client {

    public static void main(String[] args) {
        Producer producer = new Producer();

//        producer.saleProduct(10000F);

        /**
         * 动态代理。
         *
         * 特点:字节码随用随创建,随用随加载。
         * 作用:不修改源码的基础上对方法增强。
         * 分类。
         *      基于接口的动态代理。
         *      基于子类的动态代理。
         *
         * 基于接口的动态代理。
         *      设计的类:Proxy。
         *      提供者:JDK 官方。
         *
         * 如何创建代理对象。
         *      使用 Proxy 类中的 newProxyInstance(); 方法。
         *
         * 创建代理对象的要求。
         *      被代理类至少实现一个接口,如果没有则不能使用。
         *
         * newInstance() 方法的参数。
         *      - newInstance() 方法的参数。
         *
         * > - loader: ClassLoader ——> 类加载器。
         * > ~ 用于加载代理对象的字节码。和被代理对象使用相同的类加载器。(固定写法。.getClass().getClassLoader())。
         * >
         * > - interfaces: Class<?>[]
         * > ~ 用于让代理对象和被代理对象有相同的方法。(有相同的方法:实现同一接口)。(固定写法。.getClass().getInterfaces())。
         * >
         * > - h: InvocationHandler
         * > ~ 让我们写:如何代理。(用于提供增强的方法)。
         * > 一般写一个该接口的实现类(一般是匿名内部类,但不是必须的)。此接口的实现类是谁用谁写。
         */
        IProducer proxyInstance = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
                producer.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 执行被代理对象的任何接口方法都会经过该方法。
                     * @param proxy     代理对象的引用。
                     * @param method    当前执行的方法。
                     * @param args      当前执行的方法所需要的参数。
                     * @return 和被代理对象有相同的返回值。
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        Object returnValue = null;

                        // 增强的代码。
                        // 获取方法执行的参数。
                        float money = (float) args[0];
                        // 判断当前方法是不是销售。
                        if ("saleProduct".equals(method.getName())) {
                            returnValue = method.invoke(producer, money * 0.8f);// 经销商拿走 20%。
                        }
//                        return null;
//                        return method.invoke(producer, args);
                        return returnValue;
                    }
                });
        proxyInstance.saleProduct(10000f);
    }

}

~~~

销售产品,并拿到钱:9600.0


基于子类的动态代理~cglib 动态代理。

如果一个类不 implement 任何接口。==>

  • cglib 动态代理。

第三方 cglib 库。

    <dependencies>
        <!-- https://mvnrepository.com/artifact/cglib/cglib -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_3</version>
        </dependency>

    </dependencies>

在这里插入图片描述

  • create(); 方法的参数。

public Object create(Class[] argumentTypes, Object[] arguments) {

  • Class[] argumentTypes
    指定被代理对象的字节码。
package com.geek.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 模拟一个消费者。
 */
public class Client {

    public static void main(String[] args) {
        Producer producer = new Producer();

//        producer.saleProduct(10000F);

        /**
         * 动态代理。
         *
         * 特点:字节码随用随创建,随用随加载。
         * 作用:不修改源码的基础上对方法增强。
         * 分类。
         *      基于接口的动态代理。
         *      基于子类的动态代理。
         *
         * 基于子类口的动态代理。
         *      涉及的类:Enhancer。
         *      提供者:第三方 cglib 库。
         *
         * 如何创建代理对象。
         *      使用 Enhancer 类中的 create(); 方法。
         *
         * 创建代理对象的要求。
         *      被代理类不能是最终类。(需要有子类)。
         *
         * create() 方法的参数。
         * > ~ 让我们写:如何代理。(用于提供增强的方法)。
         * > 一般写一个该接口的实现类(一般是匿名内部类,但不是必须的)。此接口的实现类是谁用谁写。
         * > 我们一般写的都是该接口的子接口实现类:new MethodInterceptor() {
         *
         */
        Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
            /**
             * 执行被代理对象的任何方法都会经过此方法。
             * @param o             proxy。
             * @param method
             * @param objects       args。
             * ~ ~ ~ ~ ~ ~ ~ 以上三个参数和基于接口的动态代理 invoke(); 方法的参数一样。
             * @param methodProxy   当前执行方法的代理对象。
             * @return
             * @throws Throwable
             */
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                Object returnValue = null;

                // 增强的代码。
                // 获取方法执行的参数。
                float money = (float) objects[0];
                // 判断当前方法是不是销售。
                if ("saleProduct".equals(method.getName())) {
                    returnValue = method.invoke(producer, money * 0.8f);// 经销商拿走 20%。
                }
//                        return null;
//                        return method.invoke(producer, args);
                return returnValue;
            }
        });
        cglibProducer.saleProduct(12000F);
    }

}

~~~

销售产品,并拿到钱:9600.0


AOP 正式出场。

在软件业,AOP 为 Aspect Oriented Programming 的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP 是 OOP 的延续,是软件开发中的一个热点,也是 Spring 框架中的一个重要内容,是函数式编程的一种衍生范型。利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

  • 作用。

在程序运行期间,不修改源码对已有方法进行增强。

  • 优势。

减少重复代码。
提升开发效率。
方便维护。

  • AOP 的实现方式。

动态代理。



相关术语。

在这里插入图片描述



JoinPoint 连接点(方法)被 Advice 增强后就是 PointCut 切入点。

JoinPoint~连接点。

那些被拦截到的点。在 Spring 中,这些点指的是方法,因为 Spring 只支持方法类型的拦截点。



PointCut~切入点。

我们要对哪些 JoinPoint 进行增强的定义。

此例中,test(); 方法是连接点,但不是切入点。因为没有被增强。

package com.geek.factory;

import com.geek.service.IAccountService;
import com.geek.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 用于创建 Service 的代理对象工厂。
 */
public class BeanFactory {

    private IAccountService accountService;

    private TransactionManager transactionManager;

    public final void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * 获取 Service 代理对象。
     *
     * @return
     */
    public IAccountService getAccountService() {
        return (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        // test(); 方法不支持事务。
                        if ("test".equals(method.getName())) {
                            return method.invoke(accountService, args);
                        }

                        Object rtValue = null;

                        try {
                            // 开启事务。
                            transactionManager.beginTransaction();
                            // 执行操作。

                            rtValue = method.invoke(accountService, args);

                            // 提交事务。
                            transactionManager.commitTransaction();

                            return rtValue;
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 回滚操作。
                            transactionManager.rollbackTransaction();
                            throw new RuntimeException(e);
                        } finally {
                            // 释放连接。
                            transactionManager.release();
                        }
                    }
                });
    }

    public void setAccountService(IAccountService accountService) {
        this.accountService = accountService;
    }
}



Advice~通知 / 增强。

拦截到 JoinPoint 后要做的事情。

增强的类型。

前置增强、后置增强、异常通知、最终通知、环绕通知。



Introduction~引介。

引介是一种特殊的通知在不修改类代码的前提下,Introduction 可以在运行期为类动态地添加一些方法或 Field。



Target~目标对象。

代理的目标对象。



Warning~织入。

把增强应用到目标对象来创建新的代理对象的过程。

  • Spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。


Proxy~代理。

一个类被 AOP 织入增强后,就产生一个结果代理类。



Aspect~切面。

是切入点和通知(引介)的结合。



使用。
  • pom。
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

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

    </dependencies>
  • bean.xml。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: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">

    <!-- 配置 Spring IoC。配置 Service 对象。-->
    <bean id="accountService" class="com.geek.service.impl.AccountServiceImpl"/>

    <!-- Spring 中基于 xml 的 aop 配置。
        把通知 Bean (Logger 类)交给 Spring 管理。
        使用 <aop:config> 标签表明开始 AOP 配置。
        使用 <aop:aspect> 标签表明配置切面。
            id 属性~给切面一个唯一标识。
            ref 属性~指定通知类 Bean 的 id。
        在 <aop:aspect> 标签内部使用对应标签来配置通知的类型。
            <aop:before> ——> 前置通知。
                method 属性 ——> 用于指定 Logger 类中哪个方法是通知。
                pointCut 属性 ——> 用于指定切入点表达式。——> 对业务层的哪个方法增强。

        切入点表达式。
            execution(表达式)
            表达式。
                访问修饰符 返回值 包名.包名.....类名.方法名(参数列表)
         访问修饰符可以省略。
    -->

    <!-- 配置 Logger 类。-->
    <bean id="logger" class="com.geek.log.Logger"/>

    <aop:config>
        <aop:aspect id="logAdvice" ref="logger">
            <!-- 配置通知类型,并且建立通知方法和切入点方法的关联。-->
            <aop:before method="printLog"
                        pointcut="execution(public void com.geek.service.impl.AccountServiceImpl.saveAccount())"/>
        </aop:aspect>
    </aop:config>
</beans>

  • Class Logger。
package com.geek.log;

/**
 * 用于记录日志的工具类。提供公共代码。
 */
public class Logger {
    /**
     * 用于打印日志。计划让其在切入点方法执行之前执行(切入点方法就是业务层方法)。
     */
    public void printLog() {
        System.out.println("Logger 类中的 printLog(); 方法开始记录日志了。");
    }
}

package com.geek.service.impl;

import com.geek.service.IAccountService;

/**
 * 账户的业务层实现类。
 */
public class AccountServiceImpl implements IAccountService {
    /**
     * 模拟保存账户。
     */
    @Override
    public void saveAccount() {
        System.out.println("执行了保存账户操作。");
    }

    /**
     * 模拟更新账户。
     *
     * @param i
     */
    @Override
    public void updateAccount(int i) {
        System.out.println("执行了更新账户操作。");
    }

    /**
     * 删除账户。
     *
     * @return
     */
    @Override
    public int deleteAccount() {
        System.out.println("执行了删除账户操作。");
        return 0;
    }
}

  • 测试类。
package com.geek.aoptest;

import com.geek.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试 aop 的配置。
 */
public class AOPTest {

    public static void main(String[] args) {
        // 获取容器。
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml");
        // 获取对象。
        IAccountService accountService = (IAccountService) applicationContext.getBean("accountService");
        // 执行方法。
        accountService.saveAccount();
    }
}

结果。

Logger 类中的 printLog(); 方法开始记录日志了。
执行了保存账户操作。

Process finished with exit code 0

  • 总结。

    <!-- Spring 中基于 xml 的 aop 配置。
        把通知 BeanLogger 类)交给 Spring 管理。
        使用 <aop:config> 标签表明开始 AOP 配置。
        使用 <aop:aspect> 标签表明配置切面。
            id 属性~给切面一个唯一标识。
            ref 属性~指定通知类 Bean 的 id。
        在 <aop:aspect> 标签内部使用对应标签来配置通知的类型。
            <aop:before> ——> 前置通知。
                method 属性 ——> 用于指定 Logger 类中哪个方法是通知。
                pointCut 属性 ——> 用于指定切入点表达式。——> 对业务层的哪个方法增强。

        切入点表达式。
            execution(表达式)
            表达式。
                访问修饰符 返回值 包名.包名.....类名.方法名(参数列表)
        访问修饰符可以省略。
            public void com.geek.service.impl.AccountServiceImpl.saveAccount()
        返回值可以使用 * 表示任意返回值。
            * com.geek.service.impl.AccountServiceImpl.saveAccount()
        包名可以使用通配符。表示任意包,但是有几级包就要写几个 ** *.*.*.AccountServiceImpl.saveAccount()
        .. ——> 表示当前包及其子包。
            * *..AccountServiceImpl.saveAccount()
        类名和方法名都可以使用 * 通配。
            * *..*.*()
        参数列表可以专题直接写数据类型。
            基本类型直接写名称。
            引用类型写包名.类名的方法。java.lang.String
        任意类型(但是有参数)。——> ..
            ↓ ↓ ↓
            * *..*.*(..)
    -->

四种常用通知类型。
    <aop:config>
        <aop:aspect id="logAdvice" ref="logger">
            <!-- 配置通知类型,并且建立通知方法和切入点方法的关联。-->
            <aop:before method="beforePrintLog"
                        pointcut="execution(* *..AccountServiceImpl.saveAccount())"/>
            <aop:after-returning method="afterReturningPrintLog"
                                 pointcut="execution(* *..AccountServiceImpl.saveAccount())"/>
            <aop:after-throwing method="afterThrowingPrintLog"
                                pointcut="execution(* *..AccountServiceImpl.saveAccount())"/>
            <aop:after method="afterPrintLog"
                       pointcut="execution(* *..AccountServiceImpl.saveAccount())"/>

        </aop:aspect>
    </aop:config>
package com.geek.log;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 用于记录日志的工具类。提供公共代码。
 */
public class Logger {
    /**
     * 前置增强。
     */
    public void beforePrintLog() {
        System.out.println("Logger 类中的 beforePrintLog(); 方法开始记录日志了。");
    }

    /**
     * 后置增强。
     */
    public void afterReturningPrintLog() {
        System.out.println("Logger 类中的 afterReturningPrintLog(); 方法开始记录日志了。");
    }

    /**
     * 异常增强。
     */
    public void afterThrowingPrintLog() {
        System.out.println("Logger 类中的 afterThrowingPrintLog(); 方法开始记录日志了。");
    }

    /**
     * 最终增强。
     */
    public void afterPrintLog() {
        System.out.println("Logger 类中的 afterPrintLog(); 方法开始记录日志了。");
    }

    /**
     * 环绕通知。
     * <p>
     * 当配置环绕通知后,切入点方法没有执行,而环绕通知方法执行了。
     * <p>
     * 对比动态代理中环绕的代码,动态代理的环绕通知有明确的切入点方法调用。
     * <p>
     * Spring 框架为我们提供了一个接口,ProceedingJoinPoint,该接口有一个方法 proceed()。
     * 此方法就相当于调用切入点的方法。
     * 该接口可以作为环绕通知的方法参数。在程序执行时,Spring 框架会为我们提供该接口的实现类供我们使用。
     */
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            Object[] args = pjp.getArgs();

            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。前置。");

            rtValue = pjp.proceed(args);// 明确调用切入点方法。

            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。后置。");

            return rtValue;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。异常。");
            throw new RuntimeException(throwable);
        } finally {
            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。最终。");
        }

    }
}



pointcut-ref
<?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">

    <!-- 配置 Spring IoC。配置 Service 对象。-->
    <bean id="accountService" class="com.geek.service.impl.AccountServiceImpl"/>

    <!-- 配置 Logger 类。-->
    <bean id="logger" class="com.geek.log.Logger"/>

    <aop:config>
        <!-- 必须在切面之前。-->
        <!-- 切入点表达式。-->
        <aop:pointcut id="pt1" expression="execution(* com.geek.service.impl.AccountServiceImpl.*(..))"/>

        <aop:aspect id="logAdvice" ref="logger">
            <!-- 配置通知类型,并且建立通知方法和切入点方法的关联。-->
            <aop:before method="beforePrintLog"
                        pointcut-ref="pt1"/>
            <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"/>
            <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"/>
            <aop:after method="afterPrintLog" pointcut-ref="pt1"/>
        </aop:aspect>

    </aop:config>
</beans>



环绕通知。
            <!-- 环绕通知。-->
            <aop:around method="aroundPrintLog" pointcut-ref="pt1"/>
package com.geek.log;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 用于记录日志的工具类。提供公共代码/
 */
public class Logger {

    /**
     * 环绕通知。
     * <p>
     * 当配置环绕通知后,切入点方法没有执行,而环绕通知方法执行了。
     * <p>
     * 对比动态代理中环绕的代码,动态代理的环绕通知有明确的切入点方法调用。
     * <p>
     * Spring 框架为我们提供了一个接口,ProceedingJoinPoint,该接口有一个方法 proceed()。
     * 此方法就相当于调用切入点的方法。
     * 该接口可以作为环绕通知的方法参数。在程序执行时,Spring 框架会为我们提供该接口的实现类供我们使用。
     */
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            Object[] args = pjp.getArgs();

            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。前置。");

            rtValue = pjp.proceed(args);// 明确调用切入点方法。

            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。后置。");

            return rtValue;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。异常。");
            throw new RuntimeException(throwable);
        } finally {
            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。最终。");
        }

    }
}



注解。

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.geek"/>

    <!-- Spring aop 注解支持。-->
    <aop:aspectj-autoproxy/>
</beans>

package com.geek.log;

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

/**
 * 用于记录日志的工具类。提供公共代码。
 */
@Component("logger")
@Aspect// 表示当前类是一个切面类。
public class Logger {

    @Pointcut("execution(* com.geek.service.impl.*.*(..))")
    private void pt1() {
    }

    @Before("pt1()")
    public void beforePrintLog() {
        System.out.println("Logger 类中的 beforePrintLog(); 方法开始记录日志了。");
    }

    /**
     * 后置增强。
     */
    @After("execution(* *..AccountServiceImpl.saveAccount())")
    public void afterReturningPrintLog() {
        System.out.println("Logger 类中的 afterReturningPrintLog(); 方法开始记录日志了。");
    }

    /**
     * 异常增强。
     */
    @AfterThrowing("execution(* *..AccountServiceImpl.saveAccount())")
    public void afterThrowingPrintLog() {
        System.out.println("Logger 类中的 afterThrowingPrintLog(); 方法开始记录日志了。");
    }

    /**
     * 最终增强。
     */
    @AfterReturning("execution(* *..AccountServiceImpl.saveAccount())")
    public void afterPrintLog() {
        System.out.println("Logger 类中的 afterPrintLog(); 方法开始记录日志了。");
    }

    /**
     * 环绕通知。
     * <p>
     * 当配置环绕通知后,切入点方法没有执行,而环绕通知方法执行了。
     * <p>
     * 对比动态代理中环绕的代码,动态代理的环绕通知有明确的切入点方法调用。
     * <p>
     * Spring 框架为我们提供了一个接口,ProceedingJoinPoint,该接口有一个方法 proceed()。
     * 此方法就相当于调用切入点的方法。
     * 该接口可以作为环绕通知的方法参数。在程序执行时,Spring 框架会为我们提供该接口的实现类供我们使用。
     */
    @Around("pt1()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            Object[] args = pjp.getArgs();

            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。前置。");

            rtValue = pjp.proceed(args);// 明确调用切入点方法。

            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。后置。");

            return rtValue;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。异常。");
            throw new RuntimeException(throwable);
        } finally {
            System.out.println("Logger 类中的 aroundPrintLog(); 方法开始记录日志了。最终。");
        }

    }
}



纯注解。
package com.geek.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan(basePackages = "com.geek")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lyfGeek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值