SpringAop(一) AOP横切逻辑


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毫秒.



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值