AOP概念及相关术语
概述
AOP(Aspect Oriented Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现,在不修改源代码的情况下,给程序动态统一添加额外功能的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP的作用:
- 简化代码:把方法中固定位置的重复的代码抽取出来,让被抽取的方法更专注于自己的核心功能,提高内聚性。
- 代码增强:把特定的功能封装到切面类中,看哪里有需要,就往上套,被套用了切面逻辑的方法就被切面给增强了。
相关术语
横切关注点

AOP把软件系统分为两个部分:核心关注点和横切关注点。业务处理的主要流程是核心关注点,与之关系不大的部分是横切关注点。横切关注点的一个特点是,他们经常发生在核心关注点的多处,而各处基本相似,比如权限认证、日志、事务、异常等。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点分离开来。
通知advice
每一个横切关注点上要做的事情称为通知。通知需要写一个方法来实现。也被称为增强。
- 前置通知:在被代理的目标方法前执行
- 返回通知:在被代理的目标方法成功结束后执行(寿终正寝)
- 异常通知:在被代理的目标方法异常结束后执行(死于非命)
- 后置通知:在被代理的目标方法最终结束后执行(盖棺定论)
- 环绕通知:使用
try...catch...finally
结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置

切面 aspect
封装通知方法的类。

连接点 joinpoint
这是一个纯逻辑概念,不是语法定义的。
把方法排成一排,每一个横切位置看成x轴方向,把方法从上到下执行的顺序看成y轴,x轴和y轴的交叉点就是连接点。通俗说,就是spring允许你使用通知的地方

切入点 pointcut
定位连接点的方式。
是一个表达式,比如execution(* com.spring.service.impl.*.*(..))
。符合条件的每个方法都是一个具体的连接点。
目标
被代理的目标对象。
代理
向目标对象应用通知之后创建的代理对象。
基于注解的AOP
技术说明
动态代理分为JDK动态代理和cglib动态代理
当目标类有接口的情况使用JDK动态代理和cglib动态代理,没有接口时只能使用cglib动态代理
JDK动态代理动态生成的代理类会在com.sun.proxy包下,类名为$proxy1,和目标类实现相同的接口
cglib动态代理动态生成的代理类会和目标在在相同的包下,会继承目标类
动态代理(InvocationHandler):JDK原生的实现方式,需要被代理的目标类必须实现接口。因为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。
cglib:通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。
AspectJ:是AOP思想的一种实现。本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。
准备工作
添加依赖
<dependencies>
<!--spring context依赖-->
<!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.2</version>
</dependency>
<!--spring aop依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>6.0.2</version>
</dependency>
<!--spring aspects依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>6.0.2</version>
</dependency>
<!--junit5测试-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.1</version>
</dependency>
<!--log4j2的依赖-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.19.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.19.0</version>
</dependency>
</dependencies>
其中,有关于IOC的依赖如下:
<!--spring aop依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>6.0.2</version>
</dependency>
<!--spring aspects依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>6.0.2</version>
</dependency>
准备被代理的目标资源
接口:
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);
}
实现类:
@Component
public class CalculatorImpl implements Calculator {
@Override
public int add(int i, int j) {
int result = i + j;
System.out.println("方法内部 result = " + result);
return result;
}
@Override
public int sub(int i, int j) {
int result = i - j;
System.out.println("方法内部 result = " + result);
return result;
}
@Override
public int mul(int i, int j) {
int result = i * j;
System.out.println("方法内部 result = " + result);
return result;
}
@Override
public int div(int i, int j) {
int result = i / j;
System.out.println("方法内部 result = " + result);
return result;
}
}
创建配置类
package com.lin.aop.annoaop;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
// 表示开启包扫描
@ComponentScan(basePackages = "com.lin.aop.annoaop")
// 开启AspectJ自动代理(AOP)
@EnableAspectJAutoProxy
public class AppConfig {
}
创建切面类
//切面类
@Aspect //切面类
@Component //ioc容器
public class LogAspect {
}
切入点表达式语法

切入点表达式的作用:让切面找到要通知的目标方法
写测试类
@Test
public void testBefore() {
ApplicationContext context =new AnnotationConfigApplicationContext(AppConfig.class);
Calculator calculator = context.getBean(Calculator.class);
calculator.add(2,3);
}
测试五种通知类型
前置通知:@Before
//切面类
@Aspect //切面类
@Component //ioc容器
public class LogAspect {
@Before(value = "execution(public int com.lin.aop.annoaop.CalculatorImpl.*(..))")
public void beforeMethod() {
System.out.println("Logger-->前置通知,");
}
}
日志:
Logger-->前置通知,
方法内部 result = 5
获取连接点信息:JoinPoint
获取连接点信息(也就是目标方法相关的信息)可以在通知方法的参数位置设置JoinPoint类型的形参
//切面类
@Aspect //切面类
@Component //ioc容器
public class LogAspect {
@Before(value = "execution(public int com.lin.aop.annoaop.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint) {
// 获取连接点的签名信息
String methodName = joinPoint.getSignature().getName();
// 获取目标方法到的实参信息
Object[] args = joinPoint.getArgs();
System.out.println("Logger-->前置通知,方法名称:"+methodName+",参数:"+Arrays.toString(args));
}
}
日志:
Logger-->前置通知,方法名称:add,参数:[2, 3]
方法内部 result = 5
后置通知:@After
//切面类
@Aspect //切面类
@Component //ioc容器
public class LogAspect {
// 后置 @After()
@After(value = "execution(public int com.lin.aop.annoaop.CalculatorImpl.*(..))")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->后置通知,方法名称:"+methodName);
}
}
日志
方法内部 result = 5
Logger-->后置通知,方法名称:add
返回通知:@AfterReturning
// 相比后置通知,返回通知有一个返回结果
// returning = "result" ====> Object result
@AfterReturning(value = "execution(* com.lin.aop.annoaop.CalculatorImpl.*(..))",returning = "result")
public void afterReturningMethod(JoinPoint joinPoint,Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->返回通知,方法名称:"+methodName+",返回结果:"+result);
}
日志:
方法内部 result = 5
Logger-->返回通知,方法名称:add,返回结果:5
异常通知:@AfterThrowing
// @AfterThrowing中的属性throwing,用来将通知方法的某个形参,接收目标方法的异常
// throwing = "ex" ====> Throwable ex
@AfterThrowing(value = "execution(* com.lin.aop.annoaop.CalculatorImpl.*(..))",throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint,Throwable ex) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->异常通知,方法名称:"+methodName+",异常信息:"+ex);
}
日志
方法内部 result = 5
Logger-->异常通知,方法名称:add,异常信息:java.lang.ArithmeticException: / by zero
环绕通知:@Around
@Around("execution(* com.lin.aop.annoaop.CalculatorImpl.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
String argString = Arrays.toString(args);
Object result = null;
try {
System.out.println("环绕通知==目标方法之前执行");
//调用目标方法
result = joinPoint.proceed();
System.out.println("环绕通知==目标方法返回值之后");
}catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("环绕通知==目标方法出现异常执行");
} finally {
System.out.println("环绕通知==目标方法执行完毕执行");
}
return result;
}
环绕通知用的是
ProceedingJoinPoint joinPoint
;而其他通知用的是JoinPoint joinPoint
日志
环绕通知==目标方法之前执行
方法内部 result = 5
环绕通知==目标方法返回值之后
环绕通知==目标方法执行完毕执行
复用切入点表达式
声明:
@Pointcut(value = "execution(* com.lin.aop.annoaop.CalculatorImpl.*(..))")
public void pointCut() {}
在同一个切面类中:
//切面类
@Aspect //切面类
@Component //ioc容器
public class LogAspect {
@Before("pointCut()")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->后置通知,方法名称:"+methodName);
}
@Pointcut(value = "execution(* com.lin.aop.annoaop.CalculatorImpl.*(..))")
public void pointCut() {}
}
不在同一个类
@Aspect //切面类
@Component //ioc容器
public class LogAspect2 {
@Before("com.lin.aop.annoaop.LogAspect.pointCut()")
public void beforeMethod2(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("不在同一个类-->前置通知,方法名称:"+methodName+",参数:"+ Arrays.toString(args));
}
}
日志:
Logger-->前置通知,方法名称:add,参数:[2, 3]
不在同一个类-->前置通知,方法名称:add,参数:[2, 3]
方法内部 result = 5
各种通知的执行顺序
Spring版本5.3.x以前:
- 前置通知
- 目标操作
- 后置通知
- 返回通知或异常通知
Spring版本5.3.x以后:
- 前置通知
- 目标操作
- 返回通知或异常通知
- 后置通知
切面的优先级
使用@Order
注解可以控制切面的优先级:
- @Order(较小的数):优先级高
- @Order(较大的数):优先级低
相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。
- 优先级高的切面:外面
- 优先级低的切面:里面

切面一:
//切面类
@Order(value = 1) // 数值小,优先级高,在外层
@Aspect //切面类
@Component //ioc容器
public class LogAspect {
@Before("pointCut()")
public void beforeMethod2(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("Logger-->前置通知,方法名称:"+methodName+",参数:"+Arrays.toString(args));
}
@After(value = "pointCut()")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->后置通知,方法名称:"+methodName);
}
@Pointcut(value = "execution(* com.lin.aop.annoaop.CalculatorImpl.*(..))")
public void pointCut() {}
}
切面二:
@Order(2) // 数字大,优先级低,在内层
@Aspect //切面类
@Component //ioc容器
public class LogAspect2 {
@Before("com.lin.aop.annoaop.LogAspect.pointCut()")
public void beforeMethod2(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("不在同一个类-->前置通知,方法名称:"+methodName+",参数:"+ Arrays.toString(args));
}
@After("com.lin.aop.annoaop.LogAspect.pointCut()")
public void afterMethod2(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("不在同一个类-->后置通知,方法名称:"+methodName+",参数:"+ Arrays.toString(args));
}
}
日志:
Logger-->前置通知,方法名称:add,参数:[2, 3]
不在同一个类-->前置通知,方法名称:add,参数:[2, 3]
方法内部 result = 5
不在同一个类-->后置通知,方法名称:add,参数:[2, 3]
Logger-->后置通知,方法名称:add
基于XML的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/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.lin.aop.xmlaop"></context:component-scan>
<!--配置aop五种通知类型-->
<aop:config>
<!--配置切面类-->
<aop:aspect ref="logAspect">
<!--配置切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.lin.aop.xmlaop.CalculatorImpl.*(..))"/>
<!--配置五种通知类型-->
<!--前置通知-->
<aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
<!--后置通知-->
<aop:after method="afterMethod" pointcut-ref="pointcut"></aop:after>
<!--返回通知-->
<aop:after-returning method="afterReturningMethod" returning="result" pointcut-ref="pointcut"></aop:after-returning>
<!--异常通知-->
<aop:after-throwing method="afterThrowingMethod" throwing="ex" pointcut-ref="pointcut"></aop:after-throwing>
<!--环绕通知-->
<aop:around method="aroundMethod" pointcut-ref="pointcut"></aop:around>
</aop:aspect>
</aop:config>
</beans>
切面类
@Component //ioc容器
public class LogAspect {
//前置通知
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("Logger-->前置通知,方法名称:"+methodName+",参数:"+Arrays.toString(args));
}
// 后置通知
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->后置通知,方法名称:"+methodName);
}
// 返回通知,获取目标方法的返回值
public void afterReturningMethod(JoinPoint joinPoint,Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->返回通知,方法名称:"+methodName+",返回结果:"+result);
}
// 异常通知 获取到目标方法异常信息
//目标方法出现异常,这个通知执行
public void afterThrowingMethod(JoinPoint joinPoint,Throwable ex) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->异常通知,方法名称:"+methodName+",异常信息:"+ex);
}
// 环绕通知
public Object aroundMethod(ProceedingJoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
String argString = Arrays.toString(args);
Object result = null;
try {
System.out.println("环绕通知==目标方法之前执行");
//调用目标方法
result = joinPoint.proceed();
System.out.println("环绕通知==目标方法返回值之后");
}catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("环绕通知==目标方法出现异常执行");
} finally {
System.out.println("环绕通知==目标方法执行完毕执行");
}
return result;
}
}
测试
@Test
public void testAdd() {
ApplicationContext context = new ClassPathXmlApplicationContext("beanaop.xml");
Calculator calculator = context.getBean(Calculator.class);
calculator.add(4,3);
}
日志
Logger-->前置通知,方法名称:add,参数:[4, 3]
环绕通知==目标方法之前执行
方法内部 result = 7
环绕通知==目标方法返回值之后
环绕通知==目标方法执行完毕执行
Logger-->返回通知,方法名称:add,返回结果:7
Logger-->后置通知,方法名称:add
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1909773034@qq.com