Spring之AOP
1 AOP基本概念
1.1 概述
AOP(Aspect Oriented Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现,在不修改源代码的情况下,给程序动态统一添加额外功能的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
相关术语:
- 横切关注点
每个附加功能,如用户验证、日志管理、事务处理、数据缓存都属于横切关注点。 - 通知(增强)
增强,通俗说,就是你想要增强的功能,比如 安全,事务,日志等。
每一个横切关注点上要做的事情都需要写一个方法来实现,这样的方法就叫通知方法。
通知分为前置通知、后置通知、返回通知、异常通知、环绕通知。 - 切面
封装通知方法的类。 - 目标
被代理的目标对象。 - 代理
向目标对象应用通知之后创建的代理对象。 - 连接点
spring允许你使用通知的地方 - 切入点
定位连接点的方式,Spring 的 AOP 技术可以通过切入点定位到特定的连接点。通俗说,要实际去增强的方法。
1.2 作用
- 简化代码
把方法中固定位置的重复的代码抽取出来,让被抽取的方法更专注于自己的核心功能,提高内聚性。 - 代码增强
把特定的功能封装到切面类中,看哪里有需要,就往上套,被套用了切面逻辑的方法就被切面给增强了。
2 基于注解的AOP
2.1 基础依赖
<dependencies><!--spring context依赖--><!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId></dependency><!--spring aop依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId></dependency><!--spring aspects依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId></dependency><!--junit5测试--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><scope>test</scope></dependency><!--log4j2的依赖--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-slf4j2-impl</artifactId></dependency></dependencies>
2.2 基础类创建
被代理类
/*** @author giserDev* @description* @date 2024-01-06 23:41:26*/
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);
}/*** @author giserDev* @description* @date 2024-01-06 23:41:55*/
@Service
public class CalculatorImpl implements Calculator {@Overridepublic int add(int i, int j) {int result = i + j;// 测试异常通知// int p = 1/0;System.out.println("方法内部 result = " + result);return result;}@Overridepublic int sub(int i, int j) {int result = i - j;System.out.println("方法内部 result = " + result);return result;}@Overridepublic int mul(int i, int j) {int result = i * j;System.out.println("方法内部 result = " + result);return result;}@Overridepublic int div(int i, int j) {int result = i / j;System.out.println("方法内部 result = " + result);return result;}
}
2.3 切面类创建
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;import java.util.Arrays;/*** @author giserDev* @description** * @Aspect 标注当前类为切面类* * @Component 将切面类交由Spring管理** 各种通知的执行顺序:* - Spring版本5.3.x以前:* - 前置通知* - 目标操作* - 后置通知* - 返回通知或异常通知** - Spring版本5.3.x以后:* - 前置通知* - 目标操作* - 返回通知或异常通知* - 后置通知** @date 2024-01-07 17:22:19*/
@Aspect
@Component
public class LogAspect {/*** 前置通知:使用@Before注解标识,在被代理的目标方法前执行* @param joinPoint 连接点*/@Before(value = "execution(* com.giser.spring6.aop.impl.CalculatorImpl.*(..))")public void beforeAspectMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();String argStr = Arrays.toString(joinPoint.getArgs());System.out.println("切面-->前置通知,方法名:" + methodName + ",参数:" + argStr);}/*** 后置通知:使用@After注解标识,在被代理的目标方法最终结束后执行** @param joinPoint 连接点*/@After(value = "execution(* com.giser.spring6.aop.impl.CalculatorImpl.*(..))")public void afterAspectMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();String argStr = Arrays.toString(joinPoint.getArgs());System.out.println("切面-->后置通知,方法名:" + methodName + ",参数:" + argStr);}/*** 返回通知:使用@AfterReturning注解标识,在被代理的目标方法成功结束后执行* @param joinPoint 连接点* @param retVal 返回值*/@AfterReturning(value = "execution(* com.giser.spring6.aop.impl.CalculatorImpl.*(..))", returning = "retVal")public void afterReturningAspectMethod(JoinPoint joinPoint, Object retVal){String methodName = joinPoint.getSignature().getName();System.out.println("切面-->返回后通知,方法名:" + methodName + ",结果:" + retVal);}/*** 异常通知:使用@AfterThrowing注解标识,在被代理的目标方法异常结束后执行* @param joinPoint 连接点* @param ex 异常*/@AfterThrowing(value = "execution(* com.giser.spring6.aop.impl.CalculatorImpl.*(..))", throwing = "ex")public void afterThrowingAspectMethod(JoinPoint joinPoint, Throwable ex){String methodName = joinPoint.getSignature().getName();System.out.println("切面-->异常通知,方法名:" + methodName + ",异常:" + ex);}/*** 环绕通知:使用@Around注解标识,使用try...catch...finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置* @param proceedingJoinPoint 连接点* @return 返回值*/@Around(value = "execution(* com.giser.spring6.aop.impl.CalculatorImpl.*(..))")public Object aroundAspectMethod(ProceedingJoinPoint proceedingJoinPoint){String methodName = proceedingJoinPoint.getSignature().getName();String argStr = Arrays.toString(proceedingJoinPoint.getArgs());System.out.println("切面-->环绕通知,方法名:" + methodName + ",参数:" + argStr);Object result = null;try {System.out.println("切面-->环绕通知-->目标对象方法执行之前");//目标对象(连接点)方法的执行result = proceedingJoinPoint.proceed();System.out.println("切面-->环绕通知-->目标对象方法返回值之后");} catch (Throwable throwable) {throwable.printStackTrace();System.out.println("切面-->环绕通知-->目标对象方法出现异常时");} finally {System.out.println("切面-->环绕通知-->目标对象方法执行完毕");}return result;}}
2.4 配置
spring-aop.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!--基于注解的AOP的实现:1、将目标对象和切面交给IOC容器管理(注解+扫描)2、开启AspectJ的自动代理,为目标对象自动生成代理3、将切面类通过注解@Aspect标识--><context:component-scan base-package="com.giser.spring6.aop" /><aop:aspectj-autoproxy /></beans>
2.5 测试
/*** @author giserDev* @description 动态代理测试* @date 2024-01-07 00:02:54*/
public class AopTest {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-aop.xml");Calculator calculator = applicationContext.getBean(Calculator.class);calculator.add(3,4);}}
2.6 切入点表达式
package com.giser.spring6.aop.aspect;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;import java.util.Arrays;/*** @author giserDev* @description 切点表达式* ① 声明:* @Pointcut(value = "execution(* com.giser.spring6.aop.impl.CalculatorImpl.*(..))")* public void pointcut(){}** 剖析:execution(public int com.giser.spring6.aop.impl.CalculatorImpl.add(int,int))* execution: 固定格式** public : 修饰符* int : 方法返回值* public int 可写为 * , 表示任意权限修饰符和返回值,如execution(* com.giser.spring6.aop.impl.*.*(..))* 用*号代替“权限修饰符”和“返回值”部分表示“权限修饰符”和“返回值”不限** com.giser.spring6.aop.impl.CalculatorImpl : 方法所在类所在全类名* 这里可以写*表示任意包名* 写*..表示任意包名且包下任意层级的包* CalculatorImpl : 包下的某个类名* 类名全部用*代替,可表示包下所有的类名,* 类名部分用*代替,如*Service可表示包下所有以Service结尾的类或接口** add : 代表方法名,* 方法名全部用*代替,表示任意的方法名* 方法名部分用*代替,如delete*,表示以delete开头的方法** (int,int) : 代表参数列表,使用(..)表示参数任意** 在包名的部分,一个“*”号只能代表包的层次结构中的一层,表示这一层是任意的。* 在包名的部分,使用“*..”表示包名任意、包的层次深度任意。* 在类名的部分,类名部分整体用*号代替,表示类名任意。* 在类名的部分,可以使用*号代替类名的一部分。* 在方法名部分,可以使用*号表示方法名任意。* 在方法名部分,可以使用*号代替方法名的一部分。* 在方法参数列表部分,使用(..)表示参数列表任意。* 在方法参数列表部分,使用(int,..)表示参数列表以一个int类型的参数开头。* 在方法参数列表部分,基本数据类型和对应的包装类型是不一样的。* 在方法返回值部分,如果想要明确指定一个返回值类型,那么必须同时写明权限修饰符* 例如:execution(public int ..Service.*(.., int)) 正确* 例如:execution(* int ..Service.*(.., int)) 错误** ② 使用:* 在同一个切面使用* @Before("pointcut()")* public void beforeAspectMethod(JoinPoint joinPoint){* String methodName = joinPoint.getSignature().getName();* String argStr = Arrays.toString(joinPoint.getArgs());* System.out.println("切面-->前置通知,方法名:" + methodName + ",参数:" + argStr);* }* 切面的优先级:* 相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。* - 优先级高的切面:外面* - 优先级低的切面:里面** 使用@Order注解可以控制切面的优先级:* - @Order(较小的数):优先级高* - @Order(较大的数):优先级低** 不在同一个切面使用* @Before("com.giser.spring6.aop.aspect.PointCutExpressionAspect.pointcut()")* public void beforeAspectMethod(JoinPoint joinPoint){* String methodName = joinPoint.getSignature().getName();* String argStr = Arrays.toString(joinPoint.getArgs());* System.out.println("切面-->前置通知,方法名:" + methodName + ",参数:" + argStr);* }** @date 2024-01-07 17:22:19**/
@Aspect
@Component
public class PointCutExpressionAspect {@Pointcut(value = "execution(* com.giser.spring6.aop.impl.*.*(..))")public void pointcut(){}/*** 前置通知:使用@Before注解标识,在被代理的目标方法前执行* @param joinPoint 连接点*/@Before("pointcut()")public void beforeAspectMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();String argStr = Arrays.toString(joinPoint.getArgs());System.out.println("切面-->前置通知,方法名:" + methodName + ",参数:" + argStr);}/*** 后置通知:使用@After注解标识,在被代理的目标方法最终结束后执行** @param joinPoint 连接点*/@After(value = "pointcut()")public void afterAspectMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();String argStr = Arrays.toString(joinPoint.getArgs());System.out.println("切面-->后置通知,方法名:" + methodName + ",参数:" + argStr);}/*** 返回通知:使用@AfterReturning注解标识,在被代理的目标方法成功结束后执行* @param joinPoint 连接点* @param retVal 返回值*/@AfterReturning(value = "pointcut()", returning = "retVal")public void afterReturningAspectMethod(JoinPoint joinPoint, Object retVal){String methodName = joinPoint.getSignature().getName();System.out.println("切面-->返回后通知,方法名:" + methodName + ",结果:" + retVal);}/*** 异常通知:使用@AfterThrowing注解标识,在被代理的目标方法异常结束后执行* @param joinPoint 连接点* @param ex 异常*/@AfterThrowing(value = "pointcut()", throwing = "ex")public void afterThrowingAspectMethod(JoinPoint joinPoint, Throwable ex){String methodName = joinPoint.getSignature().getName();System.out.println("切面-->异常通知,方法名:" + methodName + ",异常:" + ex);}/*** 环绕通知:使用@Around注解标识,使用try...catch...finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置* @param proceedingJoinPoint 连接点* @return 返回值*/@Around(value = "pointcut()")public Object aroundAspectMethod(ProceedingJoinPoint proceedingJoinPoint){String methodName = proceedingJoinPoint.getSignature().getName();String argStr = Arrays.toString(proceedingJoinPoint.getArgs());System.out.println("切面-->环绕通知,方法名:" + methodName + ",参数:" + argStr);Object result = null;try {System.out.println("切面-->环绕通知-->目标对象方法执行之前");//目标对象(连接点)方法的执行result = proceedingJoinPoint.proceed();System.out.println("切面-->环绕通知-->目标对象方法返回值之后");} catch (Throwable throwable) {throwable.printStackTrace();System.out.println("切面-->环绕通知-->目标对象方法出现异常时");} finally {System.out.println("切面-->环绕通知-->目标对象方法执行完毕");}return result;}}
3 基于xml的AOP
3.1 基础依赖
<dependencies><!--spring context依赖--><!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId></dependency><!--spring aop依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId></dependency><!--spring aspects依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId></dependency><!--junit5测试--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><scope>test</scope></dependency><!--log4j2的依赖--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-slf4j2-impl</artifactId></dependency></dependencies>
3.2 基础类创建
被代理类
/*** @author giserDev* @description* @date 2024-01-06 23:41:26*/
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);
}/*** @author giserDev* @description* @date 2024-01-06 23:41:55*/
@Service
public class CalculatorImpl implements Calculator {@Overridepublic int add(int i, int j) {int result = i + j;// 测试异常通知// int p = 1/0;System.out.println("方法内部 result = " + result);return result;}@Overridepublic int sub(int i, int j) {int result = i - j;System.out.println("方法内部 result = " + result);return result;}@Overridepublic int mul(int i, int j) {int result = i * j;System.out.println("方法内部 result = " + result);return result;}@Overridepublic int div(int i, int j) {int result = i / j;System.out.println("方法内部 result = " + result);return result;}
}
3.3 切面类创建
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;import java.util.Arrays;/*** @author giserDev* @description 切点表达式* ① 声明:* @Pointcut(value = "execution(* com.giser.spring6.aop.impl.CalculatorImpl.*(..))")* public void pointcut(){}** 剖析:execution(public int com.giser.spring6.aop.impl.CalculatorImpl.add(int,int))* execution: 固定格式** public : 修饰符* int : 方法返回值* public int 可写为 * , 表示任意权限修饰符和返回值,如execution(* com.giser.spring6.aop.impl.*.*(..))* 用*号代替“权限修饰符”和“返回值”部分表示“权限修饰符”和“返回值”不限** com.giser.spring6.aop.impl.CalculatorImpl : 方法所在类所在全类名* 这里可以写*表示任意包名* 写*..表示任意包名且包下任意层级的包* CalculatorImpl : 包下的某个类名* 类名全部用*代替,可表示包下所有的类名,* 类名部分用*代替,如*Service可表示包下所有以Service结尾的类或接口** add : 代表方法名,* 方法名全部用*代替,表示任意的方法名* 方法名部分用*代替,如delete*,表示以delete开头的方法** (int,int) : 代表参数列表,使用(..)表示参数任意** 在包名的部分,一个“*”号只能代表包的层次结构中的一层,表示这一层是任意的。* 在包名的部分,使用“*..”表示包名任意、包的层次深度任意。* 在类名的部分,类名部分整体用*号代替,表示类名任意。* 在类名的部分,可以使用*号代替类名的一部分。* 在方法名部分,可以使用*号表示方法名任意。* 在方法名部分,可以使用*号代替方法名的一部分。* 在方法参数列表部分,使用(..)表示参数列表任意。* 在方法参数列表部分,使用(int,..)表示参数列表以一个int类型的参数开头。* 在方法参数列表部分,基本数据类型和对应的包装类型是不一样的。* 在方法返回值部分,如果想要明确指定一个返回值类型,那么必须同时写明权限修饰符* 例如:execution(public int ..Service.*(.., int)) 正确* 例如:execution(* int ..Service.*(.., int)) 错误** ② 使用:* 在同一个切面使用* @Before("pointcut()")* public void beforeAspectMethod(JoinPoint joinPoint){* String methodName = joinPoint.getSignature().getName();* String argStr = Arrays.toString(joinPoint.getArgs());* System.out.println("切面-->前置通知,方法名:" + methodName + ",参数:" + argStr);* }** 不在同一个切面使用* @Before("com.giser.spring6.aop.aspect.PointCutExpressionAspect.pointcut()")* public void beforeAspectMethod(JoinPoint joinPoint){* String methodName = joinPoint.getSignature().getName();* String argStr = Arrays.toString(joinPoint.getArgs());* System.out.println("切面-->前置通知,方法名:" + methodName + ",参数:" + argStr);* }** 切面的优先级:* 相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。* - 优先级高的切面:外面* - 优先级低的切面:里面** 使用@Order注解可以控制切面的优先级:* - @Order(较小的数):优先级高* - @Order(较大的数):优先级低** @date 2024-01-07 17:22:19**/
@Aspect
@Component
//@Order(0)
public class PointCutExpressionAspect {@Pointcut(value = "execution(* com.giser.spring6.aopxml.impl.*.*(..))")public void pointcut(){}/*** 前置通知:使用@Before注解标识,在被代理的目标方法前执行* @param joinPoint 连接点*/@Before("pointcut()")public void beforeAspectMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();String argStr = Arrays.toString(joinPoint.getArgs());System.out.println("切面-->前置通知,方法名:" + methodName + ",参数:" + argStr);}/*** 后置通知:使用@After注解标识,在被代理的目标方法最终结束后执行** @param joinPoint 连接点*/@After(value = "pointcut()")public void afterAspectMethod(JoinPoint joinPoint){String methodName = joinPoint.getSignature().getName();String argStr = Arrays.toString(joinPoint.getArgs());System.out.println("切面-->后置通知,方法名:" + methodName + ",参数:" + argStr);}/*** 返回通知:使用@AfterReturning注解标识,在被代理的目标方法成功结束后执行* @param joinPoint 连接点* @param retVal 返回值*/@AfterReturning(value = "pointcut()", returning = "retVal")public void afterReturningAspectMethod(JoinPoint joinPoint, Object retVal){String methodName = joinPoint.getSignature().getName();System.out.println("切面-->返回后通知,方法名:" + methodName + ",结果:" + retVal);}/*** 异常通知:使用@AfterThrowing注解标识,在被代理的目标方法异常结束后执行* @param joinPoint 连接点* @param ex 异常*/@AfterThrowing(value = "pointcut()", throwing = "ex")public void afterThrowingAspectMethod(JoinPoint joinPoint, Throwable ex){String methodName = joinPoint.getSignature().getName();System.out.println("切面-->异常通知,方法名:" + methodName + ",异常:" + ex);}/*** 环绕通知:使用@Around注解标识,使用try...catch...finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置* @param proceedingJoinPoint 连接点* @return 返回值*/@Around(value = "pointcut()")public Object aroundAspectMethod(ProceedingJoinPoint proceedingJoinPoint){String methodName = proceedingJoinPoint.getSignature().getName();String argStr = Arrays.toString(proceedingJoinPoint.getArgs());System.out.println("切面-->环绕通知,方法名:" + methodName + ",参数:" + argStr);Object result = null;try {System.out.println("切面-->环绕通知-->目标对象方法执行之前");//目标对象(连接点)方法的执行result = proceedingJoinPoint.proceed();System.out.println("切面-->环绕通知-->目标对象方法返回值之后");} catch (Throwable throwable) {throwable.printStackTrace();System.out.println("切面-->环绕通知-->目标对象方法出现异常时");} finally {System.out.println("切面-->环绕通知-->目标对象方法执行完毕");}return result;}}
3.4 配置
spring-aop.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!--基于注解的AOP的实现:1、将目标对象和切面交给IOC容器管理(注解+扫描)2、开启AspectJ的自动代理,为目标对象自动生成代理3、将切面类通过注解@Aspect标识--><context:component-scan base-package="com.giser.spring6.aopxml" /><aop:config><!--配置切面类--><aop:aspect ref="pointCutExpressionAspect"><aop:pointcut id="pointcut" expression="execution(* com.giser.spring6.aopxml.impl.CalculatorImpl.*(..))"/><aop:before method="beforeAspectMethod" pointcut-ref="pointcut"/><aop:after method="afterAspectMethod" pointcut-ref="pointcut" /><aop:after-returning method="afterReturningAspectMethod" pointcut-ref="pointcut" returning="retVal" /><aop:after-throwing method="afterThrowingAspectMethod" pointcut-ref="pointcut" throwing="ex" /><aop:around method="aroundAspectMethod" pointcut-ref="pointcut" /></aop:aspect></aop:config></beans>
3.5 测试
import com.giser.spring6.aopxml.Calculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @author giserDev* @description 动态代理测试* @date 2024-01-07 00:02:54*/
public class AopXmlTest {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-aop-xml.xml");Calculator calculator = applicationContext.getBean(Calculator.class);calculator.add(3,4);}}