Spring Boot 学习第七天:动态代理机制与Spring AOP
在Spring AOP中,Spring使用了Java的动态代理机制。这里我们将创建一个简单的切面,用于计算方法执行的时间。
首先,我们需要引入Spring AOP的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
然后,我们创建一个切面类:
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 {
@Around("execution(* com.example.demo.service.PerformanceService.*(..))")
public Object profileAllMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
String methodName = methodSignature.getMethod().getName();
// 计时开始
long start = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
// 计时结束
long end = System.currentTimeMillis();
System.out.println("Method " + methodName + " execution time: " + (end - start) + "ms");
return result;
}
}
在上述代码中,我们使用@Aspect
和@Component
注解将该类标记为切面类。@Around
注解表示我们希望建立一个围绕指定方法执行的切面。"execution(* com.example.demo.service.PerformanceService.*(..))"
是一个aspectj表达式,它匹配com.example.demo.service.PerformanceService
类中所有方法的执行。
在profileAllMethods
方法中,我们使用System.currentTimeMillis()
来计算方法执行前后的时间,并输出方法名称及执行时间。
最后,确保你的PerformanceService
类(或者你要监控的任何服务类)被Spring管理,并且方法执行会触发切面中定义的切点。
import org.springframework.stereotype.Service;
@Service
public class PerformanceService {
public void performAction() {
// 执行一些操作
}
}
在这个例子中,每当performAction
方法被调用时,都会通过切面计算并打印出方法执行的时间。这就是Spring AOP和动态代理的基本使用方法。
评论已关闭