五、Spring AOP面向切面编程(基于注解方式实现和细节)

news/2025/2/7 8:17:58/

本章概要

  • Spring AOP底层技术组成
  • 初步实现
  • 获取通知细节信息
  • 切点表达式语法
  • 重用(提取)切点表达式
  • 环绕通知
  • 切面优先级设置
  • CGLib动态代理生效
  • 注解实现小结

5.5.1 Spring AOP 底层技术组成

在这里插入图片描述

  • 动态代理(InvocationHandler):JDK原生的实现方式,需要被代理的目标类必须实现接口。因为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。
  • cglib:通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。
  • AspectJ:早期的AOP实现的框架,SpringAOP借用了AspectJ中的AOP注解。

5.5.2 初步实现

  1. 加入依赖
<!-- spring-aspects会帮我们传递过来aspectjweaver -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>6.0.6</version>
</dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>6.0.6</version>
</dependency>
  1. 准备接口
public interface Calculator {int add(int i, int j);int sub(int i, int j);int mul(int i, int j);int div(int i, int j);}
  1. 纯净实现类package com.atguigu.proxy;
/*** 实现计算接口,单纯添加 + - * / 实现! 掺杂其他功能!*/
@Component
public class CalculatorPureImpl implements Calculator {@Overridepublic int add(int i, int j) {int result = i + j;return result;}@Overridepublic int sub(int i, int j) {int result = i - j;return result;}@Overridepublic int mul(int i, int j) {int result = i * j;return result;}@Overridepublic int div(int i, int j) {int result = i / j;return result;}
}
  1. 声明切面类
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;// @Aspect表示这个类是一个切面类
@Aspect
// @Component注解保证这个切面类能够放入IOC容器
@Component
public class LogAspect {// @Before注解:声明当前方法是前置通知方法// value属性:指定切入点表达式,由切入点表达式控制当前通知方法要作用在哪一个目标方法上@Before(value = "execution(public int com.atguigu.proxy.CalculatorPureImpl.add(int,int))")public void printLogBeforeCore() {System.out.println("[AOP前置通知] 方法开始了");}@AfterReturning(value = "execution(public int com.atguigu.proxy.CalculatorPureImpl.add(int,int))")public void printLogAfterSuccess() {System.out.println("[AOP返回通知] 方法成功返回了");}@AfterThrowing(value = "execution(public int com.atguigu.proxy.CalculatorPureImpl.add(int,int))")public void printLogAfterException() {System.out.println("[AOP异常通知] 方法抛异常了");}@After(value = "execution(public int com.atguigu.proxy.CalculatorPureImpl.add(int,int))")public void printLogFinallyEnd() {System.out.println("[AOP后置通知] 方法最终结束了");}}
  1. 开启 aspectj 注解支持
  • 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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"><!-- 进行包扫描--><context:component-scan base-package="com.atguigu" /><!-- 开启aspectj框架注解支持--><aop:aspectj-autoproxy />
</beans>
  • 配置类方式
@Configuration
@ComponentScan(basePackages = "com.atguigu")
//作用等于 <aop:aspectj-autoproxy /> 配置类上开启 Aspectj注解支持!
@EnableAspectJAutoProxy
public class MyConfig {
}
  1. 测试效果
//@SpringJUnitConfig(locations = "classpath:spring-aop.xml")
@SpringJUnitConfig(value = {MyConfig.class})
public class AopTest {@Autowiredprivate Calculator calculator;@Testpublic void testCalculator(){calculator.add(1,1);}
}

输出结果:
在这里插入图片描述

5.5.3 获取通知细节信息

  1. JointPoint 接口

需要获取方法签名、传入的实参等信息时,可以在通知方法声明JoinPoint类型的形参。

  • 要点1:JoinPoint 接口通过 getSignature() 方法获取目标方法的签名(方法声明时的完整信息)
  • 要点2:通过目标方法签名对象获取方法名
  • 要点3:通过 JoinPoint 对象获取外界调用目标方法时传入的实参列表组成的数组

JointPoint.java

public class JointPoint {// @Before注解标记前置通知方法// value属性:切入点表达式,告诉Spring当前通知方法要套用到哪个目标方法上// 在前置通知方法形参位置声明一个JoinPoint类型的参数,Spring就会将这个对象传入// 根据JoinPoint对象就可以获取目标方法名称、实际参数列表@Before(value = "execution(public int com.atguigu.aop.api.Calculator.add(int,int))")public void printLogBeforeCore(JoinPoint joinPoint) {// 1.通过JoinPoint对象获取目标方法签名对象// 方法的签名:一个方法的全部声明信息Signature signature = joinPoint.getSignature();// 2.通过方法的签名对象获取目标方法的详细信息String methodName = signature.getName();System.out.println("methodName = " + methodName);int modifiers = signature.getModifiers();System.out.println("modifiers = " + modifiers);String declaringTypeName = signature.getDeclaringTypeName();System.out.println("declaringTypeName = " + declaringTypeName);// 3.通过JoinPoint对象获取外界调用目标方法时传入的实参列表Object[] args = joinPoint.getArgs();// 4.由于数组直接打印看不到具体数据,所以转换为List集合List<Object> argList = Arrays.asList(args);System.out.println("[AOP前置通知] " + methodName + "方法开始了,参数列表:" + argList);}
}
  1. 方法返回值

在返回通知中,通过 @AfterReturning 注解的 returning 属性获取目标方法的返回值!

在这里插入图片描述

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;// @Aspect表示这个类是一个切面类
@Aspect
// @Component注解保证这个切面类能够放入IOC容器
@Component
public class LogAspect {// @Before注解:声明当前方法是前置通知方法// value属性:指定切入点表达式,由切入点表达式控制当前通知方法要作用在哪一个目标方法上@Before(value = "execution(public int com.atguigu.CalculatorPureImpl.add(int,int))")public void printLogBeforeCore() {System.out.println("[AOP前置通知] 方法开始了");}@AfterReturning(value = "execution(public int com.atguigu.CalculatorPureImpl.add(int,int))")public void printLogAfterSuccess() {System.out.println("[AOP返回通知] 方法成功返回了");}// @AfterReturning注解标记返回通知方法// 在返回通知中获取目标方法返回值分两步:// 第一步:在@AfterReturning注解中通过returning属性设置一个名称// 第二步:使用returning属性设置的名称在通知方法中声明一个对应的形参@AfterReturning(value = "execution(public int Calculator.add(int,int))",returning = "targetMethodReturnValue")public void printLogAfterCoreSuccess(JoinPoint joinPoint, Object targetMethodReturnValue) {String methodName = joinPoint.getSignature().getName();System.out.println("[AOP返回通知] "+methodName+"方法成功结束了,返回值是:" + targetMethodReturnValue);}@AfterThrowing(value = "execution(public int com.atguigu.CalculatorPureImpl.add(int,int))")public void printLogAfterException() {System.out.println("[AOP异常通知] 方法抛异常了");}@After(value = "execution(public int com.atguigu.CalculatorPureImpl.add(int,int))")public void printLogFinallyEnd() {System.out.println("[AOP后置通知] 方法最终结束了");}}
  1. 异常对象捕捉

在异常通知中,通过@AfterThrowing注解的throwing属性获取目标方法抛出的异常对象

在这里插入图片描述

package com.atguigu;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;// @Aspect表示这个类是一个切面类
@Aspect
// @Component注解保证这个切面类能够放入IOC容器
@Component
@SuppressWarnings("all")
public class LogAspect {// @Before注解:声明当前方法是前置通知方法// value属性:指定切入点表达式,由切入点表达式控制当前通知方法要作用在哪一个目标方法上@Before(value = "execution(public int com.atguigu.CalculatorPureImpl.add(int,int))")public void printLogBeforeCore() {System.out.println("[AOP前置通知] 方法开始了");}@AfterReturning(value = "execution(public int com.atguigu.CalculatorPureImpl.add(int,int))")public void printLogAfterSuccess() {System.out.println("[AOP返回通知] 方法成功返回了");}// @AfterReturning注解标记返回通知方法// 在返回通知中获取目标方法返回值分两步:// 第一步:在@AfterReturning注解中通过returning属性设置一个名称// 第二步:使用returning属性设置的名称在通知方法中声明一个对应的形参@AfterReturning(value = "execution(public int Calculator.add(int,int))",returning = "targetMethodReturnValue")public void printLogAfterCoreSuccess(JoinPoint joinPoint, Object targetMethodReturnValue) {String methodName = joinPoint.getSignature().getName();System.out.println("[AOP返回通知] "+methodName+"方法成功结束了,返回值是:" + targetMethodReturnValue);}@AfterThrowing(value = "execution(public int com.atguigu.CalculatorPureImpl.add(int,int))")public void printLogAfterException() {System.out.println("[AOP异常通知] 方法抛异常了");}// @AfterThrowing注解标记异常通知方法// 在异常通知中获取目标方法抛出的异常分两步:// 第一步:在@AfterThrowing注解中声明一个throwing属性设定形参名称// 第二步:使用throwing属性指定的名称在通知方法声明形参,Spring会将目标方法抛出的异常对象从这里传给我们@AfterThrowing(value = "execution(public int Calculator.add(int,int))",throwing = "targetMethodException")public void printLogAfterCoreException(JoinPoint joinPoint, Throwable targetMethodException) {String methodName = joinPoint.getSignature().getName();System.out.println("[AOP异常通知] "+methodName+"方法抛异常了,异常类型是:" + targetMethodException.getClass().getName());}@After(value = "execution(public int com.atguigu.CalculatorPureImpl.add(int,int))")public void printLogFinallyEnd() {System.out.println("[AOP后置通知] 方法最终结束了");}}

5.5.4 切点表达式语法

  1. 切点表达式作用

AOP切点表达式(Pointcut Expression)是一种用于指定切点的语言,它可以通过定义匹配规则,来选择需要被切入的目标对象。

在这里插入图片描述

  1. 切点表达式语法

切点表达式总结

在这里插入图片描述

语法细节

  • 第一位:execution( ) 固定开头
  • 第二位:方法访问修饰符
public private 直接描述对应修饰符即可
  • 第三位:方法返回值
int String void 直接描述返回值类型

注意:
特殊情况 不考虑 访问修饰符和返回值
execution(* * ) 这是错误语法
execution( *) == 你只要考虑返回值 或者 不考虑访问修饰符 相当于全部不考虑了

  • 第四位:指定包的地址
固定的包: com.atguigu.api | service | dao
单层的任意命名: com.atguigu.*  = com.atguigu.api  com.atguigu.dao  * = 任意一层的任意命名
任意层任意命名: com.. = com.atguigu.api.erdaye com.a.a.a.a.a.a.a  ..任意层,任意命名 用在包上!
注意: ..不能用作包开头   public int .. 错误语法  com..
找到任何包下: *..
  • 第五位:指定类名称
固定名称: UserService
任意类名: *
部分任意: com..service.impl.*Impl
任意包任意类: *..*
  • 第六位:指定方法名称
语法和类名一致
任意访问修饰符,任意类的任意方法: * *..*.*
  • 第七位:方法参数
具体值: (String,int) != (int,String) 没有参数 ()
模糊值: 任意参数 有 或者 没有 (..)  ..任意参数的意识
部分具体和模糊:第一个参数是字符串的方法 (String..)最后一个参数是字符串 (..String)字符串开头,int结尾 (String..int)包含int类型(..int..)
  1. 切点表达式案例
1.查询某包某类下,访问修饰符是公有,返回值是int的全部方法
2.查询某包下类中第一个参数是String的方法
3.查询全部包下,无参数的方法!
4.查询com包下,以int参数类型结尾的方法
5.查询指定包下,Service开头类的私有返回值int的无参数方法

5.5.5 重用(提取)切点表达式

  1. 重用切点表达式优点
// @Before注解:声明当前方法是前置通知方法
// value属性:指定切入点表达式,由切入点表达式控制当前通知方法要作用在哪一个目标方法上
@Before(value = "execution(public int com.atguigu.proxy.CalculatorPureImpl.add(int,int))")
public void printLogBeforeCore() {System.out.println("[AOP前置通知] 方法开始了");
}@AfterReturning(value = "execution(public int com.atguigu.proxy.CalculatorPureImpl.add(int,int))")
public void printLogAfterSuccess() {System.out.println("[AOP返回通知] 方法成功返回了");
}@AfterThrowing(value = "execution(public int com.atguigu.proxy.CalculatorPureImpl.add(int,int))")
public void printLogAfterException() {System.out.println("[AOP异常通知] 方法抛异常了");
}@After(value = "execution(public int com.atguigu.proxy.CalculatorPureImpl.add(int,int))")
public void printLogFinallyEnd() {System.out.println("[AOP后置通知] 方法最终结束了");
}

上面案例,是我们之前编写切点表达式的方式,发现, 所有增强方法的切点表达式相同!

出现了冗余,如果需要切换也不方便统一维护!

我们可以将切点提取,在增强上进行引用即可!

  1. 同一类内部引用

提取

// 切入点表达式重用
@Pointcut("execution(public int com.atguigu.aop.api.Calculator.add(int,int)))")
public void declarPointCut() {}

注意:提取切点注解使用@Pointcut(切点表达式) , 需要添加到一个无参数无返回值方法上即可!

引用

@Before(value = "declarPointCut()")
public void printLogBeforeCoreOperation(JoinPoint joinPoint) {
  1. 不同类中引用

不同类在引用切点,只需要添加类的全限定符+方法名即可!

@Before(value = "com.atguigu.spring.aop.aspect.LogAspect.declarPointCut()")
public Object roundAdvice(ProceedingJoinPoint joinPoint) {
  1. 切点统一管理

建议:将切点表达式统一存储到一个类中进行集中管理和维护!

@Component
public class AtguiguPointCut {@Pointcut(value = "execution(public int *..Calculator.sub(int,int))")public void atguiguGlobalPointCut(){}@Pointcut(value = "execution(public int *..Calculator.add(int,int))")public void atguiguSecondPointCut(){}@Pointcut(value = "execution(* *..*Service.*(..))")public void transactionPointCut(){}
}

5.5.6 环绕通知

环绕通知对应整个 try…catch…finally 结构,包括前面四种通知的所有功能。

// 使用@Around注解标明环绕通知方法
@Around(value = "com.atguigu.aop.aspect.AtguiguPointCut.transactionPointCut()")
// 通过在通知方法形参位置声明ProceedingJoinPoint类型的形参,
// Spring会将这个类型的对象传给我们
public Object manageTransaction(ProceedingJoinPoint joinPoint) {// 通过ProceedingJoinPoint对象获取外界调用目标方法时传入的实参数组Object[] args = joinPoint.getArgs();// 通过ProceedingJoinPoint对象获取目标方法的签名对象Signature signature = joinPoint.getSignature();// 通过签名对象获取目标方法的方法名String methodName = signature.getName();// 声明变量用来存储目标方法的返回值Object targetMethodReturnValue = null;try {// 在目标方法执行前:开启事务(模拟)log.debug("[AOP 环绕通知] 开启事务,方法名:" + methodName + ",参数列表:" + Arrays.asList(args));// 过ProceedingJoinPoint对象调用目标方法// 目标方法的返回值一定要返回给外界调用者targetMethodReturnValue = joinPoint.proceed(args);// 在目标方法成功返回后:提交事务(模拟)log.debug("[AOP 环绕通知] 提交事务,方法名:" + methodName + ",方法返回值:" + targetMethodReturnValue);} catch (Throwable e) {// 在目标方法抛异常后:回滚事务(模拟)log.debug("[AOP 环绕通知] 回滚事务,方法名:" + methodName + ",异常:" + e.getClass().getName());} finally {// 在目标方法最终结束后:释放数据库连接log.debug("[AOP 环绕通知] 释放数据库连接,方法名:" + methodName);}return targetMethodReturnValue;
}

5.5.7 切面优先级设置

相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。

  • 优先级高的切面:外面
  • 优先级低的切面:里面

使用 @Order 注解可以控制切面的优先级:

  • @Order(较小的数):优先级高
  • @Order(较大的数):优先级低

在这里插入图片描述

实际意义
实际开发时,如果有多个切面嵌套的情况,要慎重考虑。例如:如果事务切面优先级高,那么在缓存中命中数据的情况下,事务切面的操作都浪费了。

在这里插入图片描述

此时应该将缓存切面的优先级提高,在事务操作之前先检查缓存中是否存在目标数据。

在这里插入图片描述

5.5.8 CGLib 动态代理生效

在目标类没有实现任何接口的情况下,Spring会自动使用cglib技术实现代理。为了证明这一点,我们做下面的测试:

@Service
public class EmployeeService {public void getEmpList() {System.out.print("方法内部 com.atguigu.aop.imp.EmployeeService.getEmpList");}
}

测试:

@Autowired
private EmployeeService employeeService;@Test
public void testNoInterfaceProxy() {employeeService.getEmpList();
}

没有接口:

在这里插入图片描述

有接口:

在这里插入图片描述

使用总结:

  • 如果目标类有接口,选择使用jdk动态代理
  • 如果目标类没有接口,选择cglib动态代理
  • 如果有接口,接口接值
  • 如果没有接口,类进行接值

5.5.9 注解实现小结

在这里插入图片描述


http://www.ppmy.cn/news/1295098.html

相关文章

Iceberg从入门到精通系列之十九:分区

Iceberg从入门到精通系列之十九&#xff1a;分区 一、认识分区二、Iceberg的分区三、Hive 中的分区四、Hive 分区问题五、Iceberg的隐藏分区六、分区变换七、分区变换 一、认识分区 分区是一种通过在写入时将相似的行分组在一起来加快查询速度的方法。 例如&#xff0c;从日志…

EBU7140 Security and Authentication(三)密钥管理;IP 层安全

B3 密钥管理 密钥分类&#xff1a; 按时长&#xff1a; short term&#xff1a;短期密钥&#xff0c;用于一次加密。long term&#xff1a;长期密钥&#xff0c;用于加密或者授权。 按服务类型&#xff1a; Authentication keys&#xff1a;公钥长期&#xff0c;私钥短期…

Golang 切片

前言 在Go语言中&#xff0c;切片是一个引用类型&#xff0c;它提供了对数组的动态窗口。切片并不存储任何数据&#xff0c;它只是描述了底层数组中的一个片段。切片的定义包括三个部分&#xff1a;指向数组的指针、切片的长度和切片的容量 基本使用 声明切片&#xff1a;声…

UI5与后端的文件交互(四)

文章目录 前言一、后端开发1. 新建管理模板表格2. 新建Function&#xff0c;动态创建文档 二、修改UI5项目1.Table里添加下载证明列2. 实现onClickDown事件 三、测试四、附 前言 这系列文章详细记录在Fiori应用中如何在前端和后端之间使用文件进行交互。 这篇的主要内容有&…

Java集合框架概念详解

目录 1. 什么是Java集合框架&#xff1f;2. 常用接口介绍3. 常用实现类介绍4. 集合框架的应用场景 前言&#xff1a; Java集合框架是Java编程中最重要的工具之一。它提供了一套强大而灵活的数据结构和算法&#xff0c;用于存储和操作数据。本文将详细介绍Java集合框架的概念、常…

华为HCIE课堂笔记第十一章 IPv6概述

第十一章 IPv6概述 11.1 背景 根本原因是&#xff1a;IPv4地址枯竭&#xff0c;IPv6是IPV4的升级版本 11.1.1 IPv6地址的优势&#xff1a; 地址空间足够大 128bit支持即插即用底层化地址结构&#xff1a;地址分配有一定的标准相比于IPv4简化了报文的头部&#xff0c;提高了…

CMakeLists.txt文件中的语法规则用于指定如何编译和链接应用程序和库

文章目录 1. 最低版本要求2. 项目名称3. 设置 C 标准4. 添加可执行文件5. 添加库文件6. 包含目录7. 链接库8. 添加子目录9. 设置变量10. 条件语句11. 安装规则12. 测试13. 定制构建类型14. 导入外部库总结 CMake 是一个跨平台的自动化构建系统&#xff0c;它使用 CMakeLists.t…

论文阅读--EFFICIENT OFFLINE POLICY OPTIMIZATION WITH A LEARNED MODEL

作者&#xff1a;Zichen Liu, Siyi Li, Wee Sun Lee, Shuicheng YAN, Zhongwen Xu 论文链接&#xff1a;Efficient Offline Policy Optimization with a Learned Model | OpenReview 发表时间&#xff1a; ICLR 2023年1月21日 代码链接&#xff1a;https://github.com/s…