Spring 复盘| AOP

Spring AOP 基础 Java 动态代理实现,阅读文章之前,你最好有以下基础:

java动态代理

1、什么是 AOP ?

AOP(Aspect Oriented Programming),即面向切面编程,它是 OOP(Object Oriented Programming,面向对象编程)的补充和完善。

在开发中,功能点通常分为横向关注点和核心关注点,核心关注点就是业务关注的点,大部分是要给用户看的。而横向关注点是用户不关心,而我们程序又必须实现的,它的特点是横向分布于核心关注点各处,比如日志功能,核心关注点:增删改查都需要实现日志功能。如果用 面向对象编程来实现的话,那增删改查都需要写一遍日志代码,这会造成非常多冗余代码,显然是不合理的。而此时,AOP 应运而生。它统一定义了,何时、何处执行这些横向功能点

2、AOP 相关术语

要理解 AOP 首先要认识以下相关术语,有这么个场景,我需要给用户模块的增删改查,实现日志功能,我现在通过这个场景来解释以上术语。

  • 连接点(joinpoint)

被拦截到的点,因为 Spring 只支持方法类型的连接点,所以在 Spring 中连接点指的就是被拦截到的方法。场景中,连接点就是增删改查方法本身。

  • 通知(advice)

所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类。
1、前置通知(Before):在目标方法被调用之前调用通知功能;
2、后置通知(After):在目标方法完成之后调用通知,此时不会关
心方法的输出是什么;
3、返回通知(After-returning):在目标方法成功执行之后调用通
知;
4、异常通知(After-throwing):在目标方法抛出异常后调用通知;
5、环绕通知(Around):通知包裹了被通知的方法,在被通知的方
法调用之前和调用之后执行自定义的行为。

  • 切点(pointcut)

对连接点进行拦截的定义,它会匹配通知所要织入的一个或多个连接点。它的格式是这样的:

《Spring 复盘| AOP》

  • 切面(aspect)

类是对物体特征的抽象,切面就是对横切关注点的抽象,它定义了切点和通知。场景中,日志功能就是这个抽象,它定义了你要对拦截方法做什么?切面是通知和切点的结合。通知和切点共同定义了切面的全部内容——它是什么,在何时和何处完成其功能。

  • 织入(weave)

将切面应用到目标对象并导致代理对象创建的过程

  • 引入(introduction)

在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段

3、注解实现 AOP

首先,定义一个加减乘除的接口,代码如下:

public interface ArithmeticCalculator {

    int add(int i, int j);

    int sub(int i, int j);

    int mul(int i, int j);

    int div(int i, int j);

}

定义一个实现类,代码如下:

@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {

    public int add(int i, int j) {
        int result = i + j;
        return result;
    }

    public int sub(int i, int j) {
        int result = i - j;
        return result;
    }

    public int mul(int i, int j) {
        int result = i * j;
        return result;
    }

    public int div(int i, int j) {
        int result = i / j;
        return result;
    }

}

定义切面,代码如下:

/**
 * 1. 加入 jar 包
 * com.springsource.net.sf.cglib-2.2.0.jar
 * com.springsource.org.aopalliance-1.0.0.jar
 * com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
 * spring-aspects-4.0.0.RELEASE.jar
 *
 * 2. 在 Spring 的配置文件中加入 aop 的命名空间。
 *
 * 3. 基于注解的方式来使用 AOP
 * 3.1 在配置文件中配置自动扫描的包: <context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan>
 * 3.2 加入使 AspjectJ 注解起作用的配置: <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
 * 为匹配的类自动生成动态代理对象.
 *
 * 4. 编写切面类:
 * 4.1 一个一般的 Java 类
 * 4.2 在其中添加要额外实现的功能.
 *
 * 5. 配置切面
 * 5.1 切面必须是 IOC 中的 bean: 实际添加了 @Component 注解
 * 5.2 声明是一个切面: 添加 @Aspect
 * 5.3 声明通知: 即额外加入功能对应的方法.
 * 5.3.1 前置通知: @Before("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(int, int))")
 * @Before 表示在目标方法执行之前执行 @Before 标记的方法的方法体.
 * @Before 里面的是切入点表达式:
 *
 * 6. 在通知中访问连接细节: 可以在通知方法中添加 JoinPoint 类型的参数, 从中可以访问到方法的签名和方法的参数.
 *
 * 7. @After 表示后置通知: 在方法执行之后执行的代码.
 */

//通过添加 @EnableAspectJAutoProxy 注解声明一个 bean 是一个切面!
@Component
@Aspect
public class LoggingAspect {

    /**
     * 在方法正常开始前执行的代码
     * @param joinPoint
     */
    @Before("execution(public int com.nasus.spring.aop.impl.*.*(int, int))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object [] args = joinPoint.getArgs();

        System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
    }

    /**
     * 在方法执行后执行的代码,无论方法是否抛出异常
     * @param joinPoint
     */
    @After("execution(* com.nasus.spring.aop.impl.*.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends");
    }


    /**
     * 在方法正常结束后执行的代码
     * 返回通知是可以访问到方法的返回值的
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value = "execution(public int com.nasus.spring.aop.impl.*.*(int, int))",
    returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends with " + result);
    }

    /**
     * 在目标方法出现异常时,会执行的代码
     * 可以访问到异常对象,可以指定在出现特定异常时再执行通知代码
     * @param joinPoint
     * @param ex
     */
    @AfterThrowing(value = "execution(public int com.nasus.spring.aop.impl.*.*(int, int))",
    throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex){
        String methodNames = joinPoint.getSignature().getName();
        System.out.println("The method " + methodNames + " occurs exception: " + ex);
    }

    /**
     * 环绕通知需要携带 ProceedingJoinPoint 类型参数
     * 环绕通知类似于动态代理的全过程; ProceedingJoinPoint 类型的参数可以决定是否执行目标方法
     * 且环绕通知必须有返回值,返回值极为目标方法的返回值
     * @param pjd
     * @return
     */
    @Around("execution(public int com.nasus.spring.aop.impl.*.*(int, int))")
    public Object aroundMethod(ProceedingJoinPoint pjd){

        Object result = null;
        String methodName = pjd.getSignature().getName();

        try {
            // 前置通知
            System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));

            // 执行目标方法
            result = pjd.proceed();

            // 返回通知
            System.out.println("The method " + methodName + " ends with " + result);
        }catch (Throwable e) {
            // 异常通知
            System.out.println("The method " + methodName + " occurs exception: " + e);
            throw new RuntimeException(e);
        }

        // 后置通知
        System.out.println("The method " + methodName + " ends");

        return result;
    }

}

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-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 自动扫描的包 -->
    <context:component-scan base-package="com.nasus.spring.aop.impl"></context:component-scan>

    <!-- 使 AspectJ 的注解起作用 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<

测试方法:

public class Main {

    public static void main(String args[]){

        // 1、创建 Spring 的 IOC 容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext_aop.xml");

        // 2、从 IOC 容器中获取 bean 实例
        ArithmeticCalculator arithmeticCalculator = ctx.getBean(ArithmeticCalculator.class);

        // 3、使用 bean
        arithmeticCalculator.add(3,6);
    }

}

测试结果:

The method add begins with [3, 6]
The method add begins with [3, 6]
The method add ends with 9
The method add ends
The method add ends
The method add ends with 9

4、xml 实现 AOP

关于 xml 的实现方式,网上发现一篇文章写的不错,此处,不再赘述,有兴趣的参考以下链接:

https://www.cnblogs.com/hongwz/p/5764917.html

5、源码地址

https://github.com/turoDog/review_spring

推荐阅读:

1、java | 什么是动态代理

2、SpringBoot | 启动原理

3、SpringBoot | 自动配置原理

《Spring 复盘| AOP》

    原文作者:一个优秀的废人
    原文地址: https://segmentfault.com/a/1190000020178697
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞