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和动态代理的基本使用方法。

最后修改于:2024年09月05日 09:20

评论已关闭

推荐阅读

DDPG 模型解析,附Pytorch完整代码
2024年11月24日
DQN 模型解析,附Pytorch完整代码
2024年11月24日
AIGC实战——Transformer模型
2024年12月01日
Socket TCP 和 UDP 编程基础(Python)
2024年11月30日
python , tcp , udp
如何使用 ChatGPT 进行学术润色?你需要这些指令
2024年12月01日
AI
最新 Python 调用 OpenAi 详细教程实现问答、图像合成、图像理解、语音合成、语音识别(详细教程)
2024年11月24日
ChatGPT 和 DALL·E 2 配合生成故事绘本
2024年12月01日
omegaconf,一个超强的 Python 库!
2024年11月24日
【视觉AIGC识别】误差特征、人脸伪造检测、其他类型假图检测
2024年12月01日
[超级详细]如何在深度学习训练模型过程中使用 GPU 加速
2024年11月29日
Python 物理引擎pymunk最完整教程
2024年11月27日
MediaPipe 人体姿态与手指关键点检测教程
2024年11月27日
深入了解 Taipy:Python 打造 Web 应用的全面教程
2024年11月26日
基于Transformer的时间序列预测模型
2024年11月25日
Python在金融大数据分析中的AI应用(股价分析、量化交易)实战
2024年11月25日
AIGC Gradio系列学习教程之Components
2024年12月01日
Python3 `asyncio` — 异步 I/O,事件循环和并发工具
2024年11月30日
llama-factory SFT系列教程:大模型在自定义数据集 LoRA 训练与部署
2024年12月01日
Python 多线程和多进程用法
2024年11月24日
Python socket详解,全网最全教程
2024年11月27日