2017-01-14 74 views
0

我使用Spring AOP的注释值,我怎样才能从注释值, 这里是我的注解:Spring AOP中获得

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
@Inherited 
@Documented 
public @interface ExecutionMethodProfiler 
{ 
    String value() default "defaultValue";; 
} 

这里是我的XML:

<aop:aspectj-autoproxy/> 
    <aop:config> 
     <aop:aspect ref="methodProfiler"> 
      <aop:pointcut id="serviceMethod" 
       expression="(execution(* com.old..*(..)) or execution(* com.test..*(..))) and @annotation(com.test.profiler.ExecutionMethodProfiler)" /> 
      <aop:around pointcut-ref="serviceMethod" method="profile"/> 
     </aop:aspect> 
    </aop:config> 

这是我的服务方法:

public void profile(ProceedingJoinPoint jointPoint) throws Throwable {} 

截至目前我可以通过使用此代码获取值:

MethodSignature signature = (MethodSignature) jointPoint.getSignature(); 
System.out.println(signature.getMethod().getAnnotation(ExecutionMethodProfiler.class).value()); 

我不喜欢它,有没有更好的方法?

回答

0

首先改变你的意见,把你的注释作为一个额外的参数:

public void profile(
    ProceedingJoinPoint jointPoint, 
    ExecutionMethodProfiler methodProfiler 
) throws Throwable {} 

然后注释绑定到你的切入点这样的说法:

<aop:around 
    pointcut="(execution(* com.old..*(..)) or execution(* com.test..*(..))) and @annotation(methodProfiler)" 
    method="profile" 
    arg-names="methodProfiler" 
/> 

我没有实际测试它,因为我现在有点忙,但基本上它是如何工作的。

+0

我试了一下,我得到的错误: 嵌套的异常是java.lang.IllegalArgumentException:错误:: 0正式无约束在切入点 – Breakidi

+0

我已更新我的答案,以便在方法签名中有第一个连接点参数。在AspectJ中,它可以是第一个或最后一个参数,但也许Spring在这里更挑剔。此外,请确保参数名称在任何地方都一样:切入点,参数名称和方法签名。否则它不能被绑定。 – kriegaex

+0

如果我更新方法签名薄,我得到这个异常: 构造函数抛出异常;嵌套异常是java.lang.IllegalStateException:期望在通知中找到2个通过名称绑定的参数,但实际上找到1个参数。 – Breakidi