PointCut将注释了某些参数的方法与注释相匹配

时间:2014-05-16 18:53:56

标签: java annotations aspectj pointcut

我有这个PointCut

@Pointcut("execution(@com.foo.bar.aspect.annotation.MyAnnotation* * (..))"
          + "&& @annotation(annot)")
public void anyFoo(MyAnnotation annot)
{

}

MyAnnotation看起来像这样:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
   boolean isFoo();

   String name;
}

假设我使用isFoo设置为true的注释注释了一个方法

@MyAnnotation(isFoo = true, name = "hello")
public void doThis()
{
   System.out.println("Hello, World");
}

如何编写切入点以使其仅与MyAnnotaionisFoo = true注释的方法匹配?

我尝试了这个,但它似乎无法正常工作

@Pointcut("execution(@com.foo.bar.aspect.annotation.MyAnnotation(isFoo = true, *) * * (..))"
          + "&& @annotation(annot)")
public void anyFoo(MyAnnotation annot)
{

}

1 个答案:

答案 0 :(得分:2)

你不能写这样的切入点,因为AspectJ不支持它。你需要使用像

这样的东西
@Pointcut("execution(@com.foo.bar.aspect.annotation.MyAnnotation* * (..))"
          + "&& @annotation(annot)")
public void anyFoo(MyAnnotation annot) {
    if (!annot.isFoo())
        return;
    // Only continue here if the annotation has the right parameter value
    // ...
}