springboot aop 实现

  1. 添加依赖:确保你的项目中包含了Spring Boot AOP的依赖,如spring-boot-starter-aop

  2. <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

  3. 创建切面类:使用@Aspect注解标记类为切面。

  4. 定义切点:使用@Pointcut注解定义你感兴趣的切点。

  5. 定义通知:使用@Before@After@AfterReturning@AfterThrowing@Around注解来定义在切点处执行的通知。

  6. import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.springframework.stereotype.Component;
     
    @Aspect
    @Component
    public class PerformanceAspect {
     
        @Pointcut("execution(* com.example.service.*.*(..))") // 切点表达式,这里以service包下所有方法为例
        public void serviceMethods() {
        }
     
        @Around("serviceMethods()")
        public Object profileAllMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
            String methodName = methodSignature.getMethod().getName();
            System.out.println("Method " + methodName + " is about to be executed");
            
            long start = System.currentTimeMillis();
            Object result = proceedingJoinPoint.proceed();
            long end = System.currentTimeMillis();
            
            System.out.println("Method " + methodName + " executed in " + (end - start) + "ms");
            return result;
        }
    }

  7. 第一个 * : 表示的是返回类型, * 表示的是所有返回类型都可以;
    包名com.xzy.controller表示的是需要拦截的包名就是com.xzy.controller包下的类;
    第二个 * : 表示的是com.xzy.controller包下的类, * 表示的是所有类都可以;
    最后一个 * : 表示的是这个类下面的方法, * 表示的是所有方法都可以;
    小括号里的 点点 : 表示的是方法的参数, 点点表示的是任意参数都可以;

  8. 在上面的例子中,@Pointcut定义了切点,即com.example.service包下所有方法的执行;@Around定义了一个环绕通知,它在方法执行前后打印出方法名称和执行时间。

    确保你的Spring Boot应用开启了AOP自动配置,这通常是默认的。如果需要显式启用,可以在配置文件中添加以下属性:

  9. spring.aop.auto=true

  10. 注解方式

  11. 使用上面的切面的话,就会切入注解是@GetMapping的所有方法。这种方式很适合处理@GetMapping,@PostMapping,@DeleteMapping不同注解有各种特定处理逻辑的场景。

    使用注解切面除了使用的是@annotation定义切入点,其它的和上面的切面没啥差别;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值