我创建了一个简单的方面来捕获公共方法的执行。这个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());
}
此建议使用此JoinPoint获取方法签名和参数。就是这样。下面是方面代码:
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());
}
对于更复杂的例子,我会推荐AspectJ:In Action一书。