Spring 复盘 | AOP

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: 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)


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


640.png


  • 切面(aspect)


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


  • 织入(weave)


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


  • 引入(introduction)


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


3、注解实现 AOP


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


1public interface ArithmeticCalculator {
 2
 3    int add(int i, int j);
 4
 5    int sub(int i, int j);
 6
 7    int mul(int i, int j);
 8
 9    int div(int i, int j);
10
11}


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


1@Component("arithmeticCalculator")
 2public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
 3
 4    public int add(int i, int j) {
 5        int result = i + j;
 6        return result;
 7    }
 8
 9    public int sub(int i, int j) {
10        int result = i - j;
11        return result;
12    }
13
14    public int mul(int i, int j) {
15        int result = i * j;
16        return result;
17    }
18
19    public int div(int i, int j) {
20        int result = i / j;
21        return result;
22    }
23
24}


定义切面,代码如下:


1/**
  2 * 1. 加入 jar 包
  3 * com.springsource.net.sf.cglib-2.2.0.jar
  4 * com.springsource.org.aopalliance-1.0.0.jar
  5 * com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
  6 * spring-aspects-4.0.0.RELEASE.jar
  7 *
  8 * 2. 在 Spring 的配置文件中加入 aop 的命名空间。
  9 *
 10 * 3. 基于注解的方式来使用 AOP
 11 * 3.1 在配置文件中配置自动扫描的包: <context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan>
 12 * 3.2 加入使 AspjectJ 注解起作用的配置: <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
 13 * 为匹配的类自动生成动态代理对象.
 14 *
 15 * 4. 编写切面类:
 16 * 4.1 一个一般的 Java 类
 17 * 4.2 在其中添加要额外实现的功能.
 18 *
 19 * 5. 配置切面
 20 * 5.1 切面必须是 IOC 中的 bean: 实际添加了 @Component 注解
 21 * 5.2 声明是一个切面: 添加 @Aspect
 22 * 5.3 声明通知: 即额外加入功能对应的方法.
 23 * 5.3.1 前置通知: @Before("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(int, int))")
 24 * @Before 表示在目标方法执行之前执行 @Before 标记的方法的方法体.
 25 * @Before 里面的是切入点表达式:
 26 *
 27 * 6. 在通知中访问连接细节: 可以在通知方法中添加 JoinPoint 类型的参数, 从中可以访问到方法的签名和方法的参数.
 28 *
 29 * 7. @After 表示后置通知: 在方法执行之后执行的代码.
 30 */
 31
 32//通过添加 @EnableAspectJAutoProxy 注解声明一个 bean 是一个切面!
 33@Component
 34@Aspect
 35public class LoggingAspect {
 36
 37    /**
 38     * 在方法正常开始前执行的代码
 39     * @param joinPoint
 40     */
 41    @Before("execution(public int com.nasus.spring.aop.impl.*.*(int, int))")
 42    public void beforeMethod(JoinPoint joinPoint){
 43        String methodName = joinPoint.getSignature().getName();
 44        Object [] args = joinPoint.getArgs();
 45
 46        System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
 47    }
 48
 49    /**
 50     * 在方法执行后执行的代码,无论方法是否抛出异常
 51     * @param joinPoint
 52     */
 53    @After("execution(* com.nasus.spring.aop.impl.*.*(..))")
 54    public void afterMethod(JoinPoint joinPoint){
 55        String methodName = joinPoint.getSignature().getName();
 56        System.out.println("The method " + methodName + " ends");
 57    }
 58
 59
 60    /**
 61     * 在方法正常结束后执行的代码
 62     * 返回通知是可以访问到方法的返回值的
 63     * @param joinPoint
 64     * @param result
 65     */
 66    @AfterReturning(value = "execution(public int com.nasus.spring.aop.impl.*.*(int, int))",
 67    returning = "result")
 68    public void afterReturning(JoinPoint joinPoint, Object result){
 69        String methodName = joinPoint.getSignature().getName();
 70        System.out.println("The method " + methodName + " ends with " + result);
 71    }
 72
 73    /**
 74     * 在目标方法出现异常时,会执行的代码
 75     * 可以访问到异常对象,可以指定在出现特定异常时再执行通知代码
 76     * @param joinPoint
 77     * @param ex
 78     */
 79    @AfterThrowing(value = "execution(public int com.nasus.spring.aop.impl.*.*(int, int))",
 80    throwing = "ex")
 81    public void afterThrowing(JoinPoint joinPoint, Exception ex){
 82        String methodNames = joinPoint.getSignature().getName();
 83        System.out.println("The method " + methodNames + " occurs exception: " + ex);
 84    }
 85
 86    /**
 87     * 环绕通知需要携带 ProceedingJoinPoint 类型参数
 88     * 环绕通知类似于动态代理的全过程;ProceedingJoinPoint 类型的参数可以决定是否执行目标方法
 89     * 且环绕通知必须有返回值,返回值极为目标方法的返回值
 90     * @param pjd
 91     * @return
 92     */
 93    @Around("execution(public int com.nasus.spring.aop.impl.*.*(int, int))")
 94    public Object aroundMethod(ProceedingJoinPoint pjd){
 95
 96        Object result = null;
 97        String methodName = pjd.getSignature().getName();
 98
 99        try {
100            // 前置通知
101            System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
102
103            // 执行目标方法
104            result = pjd.proceed();
105
106            // 返回通知
107            System.out.println("The method " + methodName + " ends with " + result);
108        }catch (Throwable e) {
109            // 异常通知
110            System.out.println("The method " + methodName + " occurs exception: " + e);
111            throw new RuntimeException(e);
112        }
113
114        // 后置通知
115        System.out.println("The method " + methodName + " ends");
116
117        return result;
118    }
119
120}


xml 配置,代码如下:


1<?xml version="1.0" encoding="UTF-8"?>
 2<beans xmlns="http://www.springframework.org/schema/beans"
 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4       xmlns:aop="http://www.springframework.org/schema/aop"
 5       xmlns:context="http://www.springframework.org/schema/context"
 6       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
 8        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 9
10    <!-- 自动扫描的包 -->
11    <context:component-scan base-package="com.nasus.spring.aop.impl"></context:component-scan>
12
13    <!-- 使 AspectJ 的注解起作用 -->
14    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
15<
16


测试方法:


1public class Main {
 2
 3    public static void main(String args[]){
 4
 5        // 1、创建 Spring 的 IOC 容器
 6        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext_aop.xml");
 7
 8        // 2、从 IOC 容器中获取 bean 实例
 9        ArithmeticCalculator arithmeticCalculator = ctx.getBean(ArithmeticCalculator.class);
10
11        // 3、使用 bean
12        arithmeticCalculator.add(3,6);
13    }
14
15}


测试结果:


1The method add begins with [3, 6]
2The method add begins with [3, 6]
3The method add ends with 9
4The method add ends
5The method add ends
6The method add ends with 9


4、xml 实现 AOP


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


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


5、源码地址


https://github.com/turoDog/review_spring

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
1月前
|
Java
Spring5入门到实战------9、AOP基本概念、底层原理、JDK动态代理实现
这篇文章是Spring5框架的实战教程,深入讲解了AOP的基本概念、如何利用动态代理实现AOP,特别是通过JDK动态代理机制在不修改源代码的情况下为业务逻辑添加新功能,降低代码耦合度,并通过具体代码示例演示了JDK动态代理的实现过程。
Spring5入门到实战------9、AOP基本概念、底层原理、JDK动态代理实现
|
1天前
|
设计模式 Java 测试技术
spring复习04,静态代理动态代理,AOP
这篇文章讲解了Java代理模式的相关知识,包括静态代理和动态代理(JDK动态代理和CGLIB),以及AOP(面向切面编程)的概念和在Spring框架中的应用。文章还提供了详细的示例代码,演示了如何使用Spring AOP进行方法增强和代理对象的创建。
spring复习04,静态代理动态代理,AOP
|
2月前
|
Java Spring
在Spring Boot中使用AOP实现日志切面
在Spring Boot中使用AOP实现日志切面
|
15天前
|
Java 数据库连接 数据库
Spring基础3——AOP,事务管理
AOP简介、入门案例、工作流程、切入点表达式、环绕通知、通知获取参数或返回值或异常、事务管理
Spring基础3——AOP,事务管理
|
1月前
|
XML Java 数据格式
Spring5入门到实战------11、使用XML方式实现AOP切面编程。具体代码+讲解
这篇文章是Spring5框架的AOP切面编程教程,通过XML配置方式,详细讲解了如何创建被增强类和增强类,如何在Spring配置文件中定义切入点和切面,以及如何将增强逻辑应用到具体方法上。文章通过具体的代码示例和测试结果,展示了使用XML配置实现AOP的过程,并强调了虽然注解开发更为便捷,但掌握XML配置也是非常重要的。
Spring5入门到实战------11、使用XML方式实现AOP切面编程。具体代码+讲解
|
28天前
|
缓存 Java 开发者
Spring高手之路22——AOP切面类的封装与解析
本篇文章深入解析了Spring AOP的工作机制,包括Advisor和TargetSource的构建与作用。通过详尽的源码分析和实际案例,帮助开发者全面理解AOP的核心技术,提升在实际项目中的应用能力。
22 0
Spring高手之路22——AOP切面类的封装与解析
|
1月前
|
存储 缓存 Java
复盘女朋友面试4个月的Spring面试题
该文章复盘了关于 Spring 的面试题,包括 Spring 的好处、Bean 的生命周期、Spring 循环依赖的解决方法、AOP 的原理以及 Spring Boot 自动装配的原理等,强调对 Spring 核心原理的清晰理解对于回答面试题的重要性。
复盘女朋友面试4个月的Spring面试题
|
1月前
|
安全 Java 开发者
Java 新手入门:Spring 两大利器IoC 和 AOP,小白也能轻松理解!
Java 新手入门:Spring 两大利器IoC 和 AOP,小白也能轻松理解!
31 1
|
1月前
|
Java Spring
Spring的AOP组件详解
该文章主要介绍了Spring AOP(面向切面编程)组件的实现原理,包括Spring AOP的基础概念、动态代理模式、AOP组件的实现以及Spring选择JDK动态代理或CGLIB动态代理的依据。
Spring的AOP组件详解
|
1月前
|
Java API Spring
Spring Boot 中的 AOP 处理
对 Spring Boot 中的切面 AOP 做了详细的讲解,主要介绍了 Spring Boot 中 AOP 的引入,常用注解的使用,参数的使用,以及常用 api 的介绍。AOP 在实际项目中很有用,对切面方法执行前后都可以根据具体的业务,做相应的预处理或者增强处理,同时也可以用作异常捕获处理,可以根据具体业务场景,合理去使用 AOP。