一、什么是AOP
AOP(Aspect-Oriented Programming)中文翻译为面向切面编程,面向方面编程
在Spring AOP中,可以理解为就是面向方法编程,是一种编程思想
二、AOP应用场景
•在不修改目标方法的源代码的前提下,Spring AOP对请求链路上的目标方法进行运行耗时的统计
∙Spring AOP底层通过动态代理机制实现对目标方法的编程,动态代理是目前面向方法编程最主流的实现技术
∙其他应用场景,比如
①给目标方法添加事务管理
②给目标方法添加访问权限控制
③对目标方法进行读写分离,save、update、delete操作一个数据源,select操作另一个数据源
编程步骤:
1.导入工程
2.编写统计目标方法运行耗时的代码
3.添加AOP相关注解@Around、@Aspect
导入依赖:在 pom.xml 文件中导入 AOP 的依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
代码案列:
java
@Aspect
@Component
public class TliasAdvice {
@Around("execution(* com.itheima.boottlias.*.*.page(..))")
//统计目标方法运行的耗时时间
public Object method(ProceedingJoinPoint pjp)throws Throwable{ //pjp代表了目标方法
//1.目标方法运行前,记录当前系统的时间start
long start = System.nanoTime();
//2.执行目标方法
Object result = pjp.proceed();
//3.目标方法运行后,记录当前系统的时间end
long end = System.nanoTime();
//4.end-start就是目标方法的运行时间
System.out.println("目标方法"+pjp.toShortString()+"的运行时间是"+(end-start)+"纳秒");
return result;
}
}
其中.page方法是自己代码中Controller中的一个方法名,此处可以举一反三

代码的实际运行效果如上图中控制台所示,其中如果运行未能显示最可能的原因就是在注解@Around中对于包的结构没有编写正确,首先依据自己的项目结构,按照层级依次写入包的名称,最后编写需要统计运行时间的方法名称