黄同学的后端和 Agent 笔记开通
Hello 后端

动手做:用 AOP 给 Service 方法计时

黄同学约 7 分钟读完免费

在 ① 建好的项目 shop 里写一个计时切面,不改任何一个 Service 方法,让每个 Service 方法被调用时都在日志里打出耗时。做完以后你会亲眼看到三件事:加切面前后 getClass() 打出来的类名变了;切面没有吞掉返回值和异常;类里面用 this 调的方法,切面套不上。

要先学过:

步骤

  1. 起 MySQL。第 7 步要打一下 ① 写的 GET /products,它要查数据库:

    bash
    cd hello-backend
    docker compose up -d --wait

    hello-backend 是动手做:用 compose 起 MySQL 和 Redis建的目录。商品数据被前面的练习改乱了也没关系,这一页只看耗时,不看数据。

  2. 先写一个要被计时的 Service。在 ~/hb-spring/shop 里建 src/main/java/com/shop/service/AopLabService.java,三个方法各演示一件事:

    java
    // src/main/java/com/shop/service/AopLabService.java
    package com.shop.service;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class AopLabService {
    
        // 故意睡 200 毫秒,当作一个慢方法
        public String slow() {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "slow 做完了";
        }
    
        // 故意抛一个异常
        public String fail() {
            throw new IllegalStateException("故意抛的异常");
        }
    
        // 在类里面调本类的 slow(),等于 this.slow()
        public String selfCall() {
            return "selfCall 调了 " + slow();
        }
    }

    再建一个 Controller,给这三个方法各开一个接口。构造方法里把 Spring 递过来的 aopLabService 是什么类打印出来:

    java
    // src/main/java/com/shop/controller/AopLabController.java
    package com.shop.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.shop.service.AopLabService;
    
    @RestController
    public class AopLabController {
    
        private final AopLabService aopLabService;
    
        public AopLabController(AopLabService aopLabService) {
            this.aopLabService = aopLabService;
            System.out.println("aopLabService 是 " + aopLabService.getClass());
        }
    
        @GetMapping("/aop-lab/slow")
        public String slow() {
            return aopLabService.slow();
        }
    
        @GetMapping("/aop-lab/fail")
        public String fail() {
            return aopLabService.fail();
        }
    
        @GetMapping("/aop-lab/self-call")
        public String selfCall() {
            return aopLabService.selfCall();
        }
    }
  3. 还没写切面,先启动一次,看 aopLabService 是什么:

    bash
    ./mvnw spring-boot:run

    在启动日志里找这一行,它夹在 Tomcat 那几行和 Started ShopApplication 之间:

    text
    aopLabService 是 class com.shop.service.AopLabService

    就是你写的那个类,后面什么都没有:现在没有任何东西要套在它外面,Spring 就没给它生成代理。看完按 Ctrl + C 停掉项目。

  4. 打开 pom.xml,在 <dependencies> 里加上 AOP 的 starter,放在 spring-boot-starter-webmvc 那一段后面。它的版本由 parent 管,不用写 <version>:

    xml
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aspectj</artifactId>
    </dependency>

    改完点 IDEA 右上角的 Maven 小按钮,让它重新读依赖。AI 常写成 spring-boot-starter-aop,那是 Spring Boot 3 的名字,Spring Boot 4 里没有了,Maven 会报这个依赖缺版本号。

  5. 写切面。建 src/main/java/com/shop/common/CostAspect.java:

    java
    // src/main/java/com/shop/common/CostAspect.java
    package com.shop.common;
    
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.springframework.stereotype.Component;
    
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    @Aspect
    @Component
    public class CostAspect {
    
        // 切点:com.shop.service 包和子包里所有类的所有方法
        @Around("execution(* com.shop.service..*.*(..))")
        public Object logCost(ProceedingJoinPoint joinPoint) throws Throwable {
            long start = System.currentTimeMillis();
            try {
                return joinPoint.proceed();   // 执行原来的方法,返回值原样交回去
            } finally {
                long cost = System.currentTimeMillis() - start;
                log.info("{} 用了 {} ms", joinPoint.getSignature().toShortString(), cost);
            }
        }
    }

    com/shop/common 这个目录 ① 没建过,IDEA 里新建类时把包名写成 com.shop.common,它会自动建好。AopLabService、ProductService 一个字都不用改。

  6. 再启动一次,找 aopLabService 那一行:

    bash
    ./mvnw spring-boot:run
    text
    aopLabService 是 class com.shop.service.AopLabService$$SpringCGLIB$$0

    类名后面多了 $$SpringCGLIB$$0:切点选中了 AopLabService 的方法,Spring 就给它生成了一个 CGLIB 代理,递给 Controller 的是代理。

  7. 在第二个终端里打几个接口,每打一个,回第一个终端看日志多了哪一行。先打慢方法:

    bash
    curl localhost:8080/aop-lab/slow
    text
    slow 做完了

    第一个终端的日志里多了一行,毫秒数以你看到的为准,比 200 多一点:

    text
    …  : AopLabService.slow() 用了 203 ms

    返回值 slow 做完了 原样回到了 curl,说明切面把 proceed() 的结果交回去了。再打 ① 写的商品接口:

    bash
    curl localhost:8080/products

    三种商品的 JSON 照样出来,日志里多了一行 ProductService.listProducts() 用了 … ms。ProductService 是 ① 写的,你没动过它,计时是切面替你套上的。ProductController 的方法没有计时,因为切点只选了 com.shop.service 包。

  8. 打会抛异常的那个:

    bash
    curl localhost:8080/aop-lab/fail
    text
    {"timestamp":"…","status":500,"error":"Internal Server Error","path":"/aop-lab/fail"}

    日志里先是一行 AopLabService.fail() 用了 0 ms,后面跟着一大段报错,往下能找到 java.lang.IllegalStateException: 故意抛的异常。切面打完耗时,异常照样抛给了 Controller,所以 curl 拿到的是 500,没有被切面吞掉。

  9. 最后打 selfCall。先别急着看日志,想一想:selfCall() 里调了 slow(),日志里会多出一行还是两行?想好了再打:

    bash
    curl localhost:8080/aop-lab/self-call
    text
    selfCall 调了 slow 做完了
    答案

    日志里只多了一行:

    text
    …  : AopLabService.selfCall() 用了 202 ms

    selfCall() 用了 200 多毫秒,可里面那次 slow() 没有单独的一行。Controller 调 selfCall() 时经过了代理,所以有计时;selfCall() 里的 slow() 就是 this.slow(),this 是代理包着的那个目标对象,这次调用在目标对象里面发生,代理根本不知道,切面也就套不上。@Transactional 在同样的写法下也不生效,在事务为什么没生效讲。

  10. 自己把切面改坏一次,看看常见的错误写法会怎样。把 logCost 换成下面这样:返回 void,proceed() 的结果扔掉,异常 catch 住只记日志。

    java
    @Around("execution(* com.shop.service..*.*(..))")
    public void logCost(ProceedingJoinPoint joinPoint) {
        long start = System.currentTimeMillis();
        try {
            joinPoint.proceed();
        } catch (Throwable e) {
            log.error("出错了", e);
        }
        log.info("用了 {} ms", System.currentTimeMillis() - start);
    }

    重启以后,再打一次 /products 和 /aop-lab/fail。先想一想 curl 会拿到什么,再打。

    答案

    两个接口都返回 200,可 curl 什么都没打出来,正文是空的。切面返回 void,Service 方法的返回值就成了 null,商品列表变成了 null,Controller 把 null 交回去,正文就是空的。/aop-lab/fail 的异常被切面 catch 住了,调用方以为成功了,也拿到一个 null。这样的切面套在全项目的 Service 上,所有查询都查不到东西、所有错误都悄悄消失,而且日志里每次都打着耗时,看着一切正常。

    看完把 logCost 改回第 5 步的写法,重启一次,/products 又能打出商品了。

做完了

第 6 步的类名带着 $$SpringCGLIB$$0,第 7、8 步 slow 和 fail 各有一行耗时、返回值和异常都照常到了 curl,第 9 步只有 selfCall 一行,就做对了。

不用了,在第一个终端按 Ctrl + C 停掉项目,到 hello-backend 目录里 docker compose stop 停掉 MySQL。CostAspect 会给后面所有 Service 方法打耗时,嫌日志太多,可以删掉它,或者照 AOP:日志和权限检查是怎样「自动」加上的 里讲的,把切点改成 @annotation(com.shop.common.LogCost),只给贴了注解的方法计时;AopLabService 和 AopLabController 只是这一页用的,删掉也行。

做不出来时

  • 第 4 步之后启动报 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-aop:jar is missing:artifactId 写成了旧名字,改成 spring-boot-starter-aspectj。
  • 编译报找不到 org.aspectj.lang:第 4 步的依赖没加上,或者加了以后没让 IDEA 重新读依赖。在终端里用 ./mvnw spring-boot:run 启动,它每次都会重新读 pom.xml。
  • 第 6 步类名还是没有 $$SpringCGLIB$$、日志里也没有耗时:看 CostAspect 上 @Aspect 和 @Component 是不是都写了,少了 @Component 它就不是 Bean,Spring 不认;再看它是不是在 com.shop 下面的包里,第一行是不是 package com.shop.common;。
  • 日志里有耗时,但 slow 那一行的毫秒数小于 200:看 slow() 里是不是 Thread.sleep(200)。
  • 第 7 步 /products 返回 500:MySQL 没起来,回第 1 步。