赞
踩
在面向切面编程(AOP)中,使用executiontime advice
来统计方法的执行时间是一种常见的做法。AOP可以使得统计执行时间逻辑与业务逻辑分离,更加灵活和可维护。以下是使用Spring AOP在Java中实现统计方法执行时间的基本示范。
首先,确保在你的pom.xml
中添加了Spring AOP和AspectJ的依赖。以下是示例:
- <dependencies>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
- <version>你的Spring版本</version>
- </dependency>
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>你的AspectJ版本</version>
- </dependency>
- </dependencies>
创建一个切面ExecutionTimeAdvice
来统计方法的执行时间。在切面内定义一个@Around
通知,该通知将会围绕目标方法执行。
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.Around;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Pointcut;
- import org.springframework.stereotype.Component;
-
- @Aspect
- @Component
- public class ExecutionTimeAdvice {
-
- @Pointcut("execution(* com.example.yourapp..*(..))") // 定义切入点表达式
- public void anyMethod() {
- // 用于Pointcut签名
- }
-
- // 统计方法执行时间的切面逻辑
- @Around("anyMethod()")
- public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
- long start = System.currentTimeMillis(); // 开始时间
- Object proceed = joinPoint.proceed(); // 执行目标方法
- long executionTime = System.currentTimeMillis() - start; // 计算执行时间
- System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
- return proceed;
- }
- }

在上述示例中,@Around
注解定义了一个通知,该通知会在anyMethod
这个切点指定的方法之前和之后执行。这里的切点表达式execution(* com.example.yourapp..*(..))
匹配com.example.yourapp
包下所有类的所有方法。通过joinPoint.proceed()
执行目标方法,并计算执行前后的时间差来得到方法执行时间。
确保Spring能够扫描到你定义的切面,你的启动类或配置类上应该有@ComponentScan
和@EnableAspectJAutoProxy
注解:
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.context.annotation.EnableAspectJAutoProxy;
-
- @SpringBootApplication
- @EnableAspectJAutoProxy // 启用AspectJ自动代理
- public class YourApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(YourApplication.class, args);
- }
- }
完成以上步骤后,你的应用就能自动记录任何方法的执行时间,并在控制台中打印出来了。这是AOP的典型应用之一,可以非常方便地进行横向功能的扩展,比如性能监控、日志记录等,而不需要侵入业务逻辑代码。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。