
Spring AOP 使用动态代理技术在运行期织入增强的代码,为了揭示 Spring AOP 底层的工作机理,有必要对涉及到的 Java 知识进行学习。
Spring AOP 使用了两种代理机制:一种是基于JDK的动态代理;另一种是基于CGLib的动态代理。之所以需要两种代理机制,很大程度上是因为 JDK 本身只提供接口的代理,而不支持类的代理。
在调用每一个目标类方法时启动方法的性能监视,在目标类方法调用完成时记录方法的花费时间。
ForumService:包含性能监视横切代码
package com.smart.proxy;
public class ForumServiceImpl implements ForumService {
public void removeTopic(int topicId) {
PerformanceMonitor.begin("com.smart.proxy.ForumServiceImpl.removeTopic");
System.out.println("模拟删除Topic记录:"+topicId);
try {
Thread.currentThread().sleep(20);
} catch (Exception e) {
throw new RuntimeException(e);
}
PerformanceMonitor.end();
}
public void removeForum(int forumId) {
PerformanceMonitor.begin("com.smart.proxy.ForumServiceImpl.removeForum");
System.out.println("模拟删除Forum记录:"+forumId);
try {
Thread.currentThread().sleep(40);
} catch (Exception e) {
throw new RuntimeException(e);
}
PerformanceMonitor.end();
}
}
每个Service类和每个业务方法体的前后都执行相同的代码逻辑:方法调用前启动PerformanceMonitor,方法调用后通知PerformanceMonitor结束性能监视并给记录性能监视结果。
PerformanceMonitor是性能监视的实现类,我们给出一个非常简单的实现版本
package com.smart.proxy;
public class PerformanceMonitor {
// 线程本地变量 performaceRecord
private static ThreadLocal<MethodPerformace> performaceRecord = new ThreadLocal<MethodPerformace>();
// 开始对某个目标类方法的监视
public static void begin(String method) {
System.out.println("begin monitor...");
MethodPerformace mp = performaceRecord.get();
if (mp == null) {
mp = new MethodPerformace(method);
performaceRecord.set(mp);
} else {
mp.reset(method);
}
}
// 结束对某个目标类方法的监视,并给出性能监视信息
public static void end() {
System.out.println("end monitor...");
MethodPerformace mp = performaceRecord.get();
mp.printPerformace();
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-64976-1.html
多学一些知识
总在说数量
非权力非战略能定而