2009-02-11 45 views
4

我想使用aspectj来剖析一个库。我的计划是为了纪念那些需要分析与注释方法:使用aspectj来剖析所选方法

@Profiled("logicalUnitOfWork")

然后还要将火之前和之后的方法,将使用logicalUnitOfWork突出异形内容的一个方面。

所以,我的切入点看起来像这样。请注意,我没有这里的注释参数;这就是事情之一,我不知道该怎么做:

pointcut profiled() : execution(@Profiled * *()); 

before() : profiled() { 
    // : the profiled logical name is in this variable: 
String logicalEventType; 
Profiler.startEvent (logicalEventType); 
} 

after() returning : profiled() { 
    // : the profiled logical name is in this variable: 
String logicalEventType; 
    Profiler.endEvent (logicalEventType); 
} 

被分析会这样被定义的方法:

@Profiled("someAction") 
public void doAction (args...) {} 

总之,我怎么能得到@Profiled的价值注释到方面?我不需要根据该值限制发生哪些分析,我只是需要它对建议可见。另外,我是否需要将注释的保留设置为运行时才能运行,或者我是否可以保留类级保留?

回答

2

我不知道这是否是做的最好的方法,但你可以尝试这样的:既然你需要在运行时访问注释值,你将不得不设置@Retention

 

    pointcut profiledOperation(Profiled p) : 
     execution(@Profiled * *()) && @annotation(p); 

    before(Profiled p): profiledOperation(p) 
    { 
     System.out.println("Before " + p.value()); 
    } 

    after(Profiled p): profiledOperation(p) 
    { 
     System.out.println("After " + p.value()); 
    } 
 

RUNTIME

+0

也有一定的帮助,但最好我想有注解的类只保留文件。 AspectJ编织发生在那一点,所以我希望它能够获得价值。 – 2009-02-15 16:29:04

1

我做了一些类似的事,然后用“默认值”注释字段。我试图将它适用于注释的方法,这些方法应该可以找到。当然,您应该在这里添加一些错误检查和空测试,因为为了简洁起见,我已经将其删除了。

您可以使用连接点的静态部分来获取注释的值。

private String getOperationName(final JoinPoint joinPoint) { 
    MethodSignature methodSig = (MethodSignature) joinPoint 
     .getStaticPart() 
     .getSignature(); 
    Method method = methodSig.getMethod(); 
    Profiled annotation = method.getAnnotation(Profiled.class); 
    return annotation.value(); 
} 

为了避免过多的反映,它可能是一个好主意,用around建议改为:

around(): profiled() { 
    String opName = getOperationName(thisJoinPoint); 
    Profiler.startEvent(opName); 
    proceed(); 
    Profiler.endEvent(opName); 
}