Aop 是面向切面编程,是在业务代码中可以织入其他公共代码(性能监控等),现在用普通的方法实现AOP
1、首先存在的肯定是业务类
</pre><p></p><p><pre name="code" class="java">/**
*
*/
package com.baobaotao.proxy;
/**
*
* 业务类
* @author Administrator
*
*/
public class ForumServiceImpl
{
@SuppressWarnings("static-access")
public void removeTopic(int topic)
{
PerformanceMonitor.begin("removeTopic");
System.out.println("模拟删除topic记录"+topic);
try
{
Thread.currentThread().sleep(20);
}
catch(Exception e)
{
throw new RuntimeException(e);
}
PerformanceMonitor.end();
}
@SuppressWarnings("static-access")
public void removeMessage(int messageId)
{
System.out.println("模拟删除messageId记录"+messageId);
PerformanceMonitor.begin("removeMessage");
try
{
Thread.currentThread().sleep(40);
}
catch(Exception e)
{
throw new RuntimeException(e);
}
PerformanceMonitor.end();
}
}
2、然后是性能监控的实现类
/**
*
*/
package com.baobaotao.proxy;
/**
*
* @author Administrator
*
*/
public class PerformanceMonitor
{
// 通过一个ThreadLocal保存调用线程先关的性能监视信息
private static ThreadLocal<MethodPerformance> performanceRecord = new ThreadLocal<MethodPerformance>();
//启动对某一目标方法的监控
public static void begin(String method)
{
System.out.println("begin monitor");
MethodPerformance mp = new MethodPerformance(method);
performanceRecord.set(mp);
}
public static void end()
{
System.out.println("end monitor");
MethodPerformance mp = performanceRecord.get();
//打印性能监控的结果
mp.printPerformance();
}
}
3、然后是记录信息监控的类
package com.baobaotao.proxy;
/**
* 性能监控的类
* @author Administrator
*
*/
public class MethodPerformance
{
private long begin;
private long end;
private String serviceMethod;
//记录目标类方法开始执行点的系统时间
public MethodPerformance(String serviceMethod)
{
this.serviceMethod = serviceMethod;
this.begin = System.currentTimeMillis();
}
//获取目标方法执行完成后的系统时间,并且进而计算出目标类方法执行的时间
public void printPerformance()
{
end = System.currentTimeMillis();
long elapse = end - begin;
System.out.println(serviceMethod +"花费"+elapse+"毫秒."); //报告执行时间
}
}
4、最后是测试类
/**
*
*/
package com.baobaotao.proxy;
/**
* @author Administrator
*
*/
public class TestForumService
{
public static void main(String[] args) {
ForumServiceImpl forumService = new ForumServiceImpl();
forumService.removeTopic(10);
forumService.removeMessage(20);
}
}
输出结果是:
begin monitor
模拟删除topic记录10
end monitor
com.baobaotao.proxy.ForumServiceImpl.removeTopic花费20毫秒.
模拟删除messageId记录20
begin monitor
end monitor
com.baobaotao.proxy.ForumServiceImpl.removeMessage花费40毫秒.