AOP(例如AspectJ,SpringAOP)在下面的方法的切入点处理(建议)横切关注点是方便的,
“三明治”代码
methodA {
crosscut code
user code A
crosscut code
}
methodB {
crosscut code
user code B
crosscut code
}
AOP是否倾向于横切关注与下面的用户代码重叠?怎么样?
“Spaghetti”代码
methodX {
user code x1
crosscut code
user code x2
crosscut code
}
methodY {
user code y1
crosscut code
user code y2
crosscut code
}
谢谢!
解决方法:
Spring AOP无济于事,因为它只能理解execution()切入点.
AspectJ包含更多切入点,包括withincode()构造,听起来像你想要的:
withincode(* YourClass.methodX(. .))
这允许您建议给定方法执行中的所有连接点
阅读AspectJ in Action以获取更多信息,这是一本关于AspectJ和Spring AOP的非常好的书.
编辑:
这是一些示例代码:
package com.dummy.aspectj;
import java.util.Arrays;
import java.util.Collections;
public class DummyClass{
public static void main(final String[] args){
System.out.println(Arrays.asList("One", Collections.singleton("Two")));
System.out.println("Enough?");
}
}
package com.dummy.aspectj;
import java.util.Arrays;
public aspect DummyAspect{
pointcut callWithinMain() :
withincode(* com.dummy.aspectj.DummyClass.main(..)) // anything inside DummyClass.main
&& call(* *.*(..)); // but only method calls
before() : callWithinMain() {
System.out.println("\n***************************************************");
System.out.println("** Calling:\n**\t"
+ thisJoinPointStaticPart.getSignature()
+ "\n** with arguments:\n**\t "
+ Arrays.deepToString(thisJoinPoint.getArgs()) );
System.out.println("***************************************************\n");
}
}
从Eclipse / AJDT运行DummyClass会生成以下输出:
***************************************************
** Calling:
** Set java.util.Collections.singleton(Object)
** with arguments:
** [Two]
***************************************************
***************************************************
** Calling:
** List java.util.Arrays.asList(Object[])
** with arguments:
** [[One, [Two]]]
***************************************************
***************************************************
** Calling:
** void java.io.PrintStream.println(Object)
** with arguments:
** [[One, [Two]]]
***************************************************
[One, [Two]]
***************************************************
** Calling:
** void java.io.PrintStream.println(String)
** with arguments:
** [Enough?]
***************************************************
Enough?