[Java2023] Day13.4 -AOP入门Demo-面向方法编程

57 阅读1分钟

面向方法编程, 面向切面编程

介绍

  • 典型应用场景:
  1. 记录操作日志
  2. 权限控制
  3. 事务管理
  • 优势:
  1. 代码无入侵(无需修改原代码, 就可以实现功能)
  2. 减少重复代码
  3. 提高效率
  4. 维护方便
  • 案例
  1. 在不修改原代码的情况下, 统计每个Service层方法的运行时间

image.png

代码

  • 1.添加pom依赖
<!--AOP-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • 2.添加AOP类
package com.tlias.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect // 定义为AOP类
public class TimeAspect {

    @Around("execution(* com.tlias.service.*.*(..))") // 切入点表达式
    public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1.记录开始时间
        long begin = System.currentTimeMillis();

        // 2.调用原始方法运行
        Object result = joinPoint.proceed();

        // 3.记录结束时间,计算执行耗时
        long end = System.currentTimeMillis();

        log.info(joinPoint.getSignature() + "执行耗时,{}ms", (end - begin));

        return result; //注意要return 否则service层可能获取不到post数据
    }
}