我想将“跟踪”消息添加到我的所有公共方法中,如下所示:
public void foo(s:String, n:int) { // log is a log4j logger or any other library log.trace(String.format("Enter foo with s: %s, n: %d", s, n)) ... log.trace("Exit foo") }
现在,我想log.trace使用AOP(和字节码检测)将所有这些自动添加到我的方法中。我在想AspectJ。是否有意义?您知道任何开放源代码吗?
log.trace
AspectJ
我创建了一个简单的方面来捕获公共方法的执行。该AspectJ代码的核心是切入点定义:
pointcut publicMethodExecuted(): execution(public * *(..));
在这里,我们将捕获任何包,任何类,具有任意数量的参数,具有任何返回类型的所有公共方法。
建议执行可以在下面的代码段中可视化:
after(): publicMethodExecuted() { System.out.printf("Enters on method: %s. \n", thisJoinPoint.getSignature()); Object[] arguments = thisJoinPoint.getArgs(); for (int i =0; i < arguments.length; i++){ Object argument = arguments[i]; if (argument != null){ System.out.printf("With argument of type %s and value %s. \n", argument.getClass().toString(), argument); } } System.out.printf("Exits method: %s. \n", thisJoinPoint.getSignature()); }
该建议使用thisJoinPoint获取方法签名和参数。就是这样。这是方面代码:
public aspect LogAspect { pointcut publicMethodExecuted(): execution(public * *(..)); after(): publicMethodExecuted() { System.out.printf("Enters on method: %s. \n", thisJoinPoint.getSignature()); Object[] arguments = thisJoinPoint.getArgs(); for (int i =0; i < arguments.length; i++){ Object argument = arguments[i]; if (argument != null){ System.out.printf("With argument of type %s and value %s. \n", argument.getClass().toString(), argument); } } System.out.printf("Exits method: %s. \n", thisJoinPoint.getSignature()); }