spring-aop计算方法耗时
时间: 2023-08-27 17:07:10 浏览: 61
可以通过在方法前后添加时间戳,然后计算时间差来计算方法耗时。也可以使用Spring AOP的拦截器,在方法执行前后记录时间戳,然后计算时间差。以下是一个使用Spring AOP计算方法耗时的示例:
1. 定义一个切面类,实现MethodInterceptor接口
```java
@Component
@Aspect
public class TimingAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = invocation.proceed();
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println(invocation.getMethod().getName() + " 方法耗时:" + elapsedTime + "ms");
return result;
}
}
```
2. 在配置文件中启用AOP,并将切面类作为切点
```xml
<aop:aspectj-autoproxy />
<bean id="timingAspect" class="com.example.TimingAspect" />
<aop:config>
<aop:aspect ref="timingAspect">
<aop:pointcut expression="execution(* com.example.service.*.*(..))" />
<aop:around method="invoke" />
</aop:aspect>
</aop:config>
```
3. 在需要计算耗时的方法上加上@LogExecutionTime注解
```java
@Service
public class MyService {
@LogExecutionTime
public void doSomething() {
// do something
}
}
```
4. 定义@LogExecutionTime注解和切面类
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecutionTime {
}
@Component
@Aspect
public class TimingAspect {
@Around("@annotation(com.example.LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println(joinPoint.getSignature().getName() + " 方法耗时:" + elapsedTime + "ms");
return result;
}
}
```
这样,在调用doSomething方法时,就会输出方法耗时的信息。