---
title: "打印出，入口参数和执行时间--AOP简单应用"
author: "ginge"
date: "2009-03-03T18:05:22Z"
tags: []
slug: "aop"
draft: false
lastmod: "2009-03-03T18:05:22Z"
id: 342455
url: "https://ginge.iteye.com/blog/342455"
---

项目进入ST的时候，为了定位问题处于哪个模块。需要明确知道出入中的参数的值以追寻问题的根源。这经常需要编写大量的打印语句。可能有些人会写这些东西，但是有些人却忘记写了。也有人通过完整的Unit Testing确信自己的代码没有问题。可是当问题出现时，事情不会这么容易解决。因为人家可能也做了测试，只不过漏了测试某些分支而导致问题发生了。这个时候就需要证据了。一种方法是把出入口参数的值一一打印出来。可是这些语句要是散落在各个类里就太丑陋了，维护起来也费劲。

 

利用AOP我们可以一下这方面的事情。以下的主要的代码片段：

```
public Object cut(ProceedingJoinPoint pjp)
			throws Throwable {
		
		
		String instanceMethod = 
			pjp.getTarget().getClass() + "@" + pjp.getTarget().hashCode() + "]"+"." + pjp.getSignature().getName();
		if(this.isPrintArguments())
		{
			this.printArguments(instanceMethod, pjp.getArgs());
		}
		
		
		Object rel = null;
		
		long start = System.nanoTime();
		
		try
		{
			rel = pjp.proceed();
		}catch(Exception e)
		{
			if(this.isCatchException())
			{
				if(log.isErrorEnabled())
				{
					log.error("Exception occure while executing.", e);
				}
			}
			
			throw e;
		}
		
		long end = System.nanoTime();
		
		if(this.isPrintInvocationTime())
		{
			if(log.isDebugEnabled())
			{
				log.debug("["+(end - start)+"] nanoseconds elapsed executing [" + instanceMethod );
			}
		}
		
		
		if(this.isPrintReturnValue())
		{
			printReturnVal(rel);
		}
		
		log.debug("");
		
		return rel;
	}
```

 

样本配置如下：

```
<aop:config>
		<aop:aspect id="com.bee.fw.core.methodInvocationAspect" ref="com.bee.fw.core.MethodInvocationDetailsInspector">
			<aop:pointcut id="com.bee.fw.core.cutExpresseion"
				expression="execution(* com.bee.fw.debug.Aspect.*(..))" />
			<aop:around pointcut-ref="com.bee.fw.core.cutExpresseion" method="cut" />
		</aop:aspect>
	</aop:config>
	
	<bean id="com.bee.fw.core.MethodInvocationDetailsInspector" class="com.bee.fw.debug.MethodInvocationDetailsInspector">
		<property name="printInvocationTime" value="true" />
		<property name="order" value="100" />
	</bean>
	
	<bean id="com.bee.fw.core.Aspect" class="com.bee.fw.debug.Aspect">
	</bean>
```

 

这个代码依赖的类库有：

Spring &gt;= 2.0

Commons-io &gt;= 1.3.1

Commons-logging &gt;=1.1

Commons-beanUtils &gt; 1.8.0

Log4j &gt;= 1.2.13

 

有兴趣的可以查看附件的源码和程序执行的效果。