Pointcut matching methods with annotated parameters

天涯浪子 提交于 2019-11-30 00:23:21
Espen

It was an interesting problem, so I created a little sample application to solve the case! (And improved it with Sinuhe's feedback afterwards.)

I have created a DemoController class that should work as an example for the aspect:

@Controller
public class DemoController {

    public void soSomething(String s, @MyParamAnnotation Double d, Integer i) {
    }

    public void doSomething(String s, long l, @MyParamAnnotation int i) {
    }

    public void doSomething(@MyParamAnnotation String s) {
    }

    public void doSomething(long l) {
    }
}

The aspect that will add a join point on the first three methods, but not the last method where the parameter isn't annotated with @MyParamAnnotation:

@Aspect
public class ParameterAspect {

    @Pointcut("within(@org.springframework.stereotype.Controller *)")
    public void beanAnnotatedWithAtController() {
    }

    @Pointcut("execution(public * *(.., @aspects.MyParamAnnotation (*), ..))")
    public void methodWithAnnotationOnAtLeastOneParameter() {
    }

    @Before("beanAnnotatedWithAtController() " 
            + "&& methodWithAnnotationOnAtLeastOneParameter()")
    public void beforeMethod() {    
        System.out.println("At least one of the parameters are " 
                  + "annotated with @MyParamAnnotation");
    }
}

The first pointcut will create a joinpoint on all methods inside classes marked with @Controller.

The second pointcut will add a joinpoint when the following conditions are met:

  • public method
  • first * is a wildcard for every return type.
  • second * is a wildcard for all methods in all classes.
  • (.., matches zero to many parameters of any type before the annotated parameter.
  • @aspects.MyParamAnnotation (*), matches a parameter annotated with the given annotation.
  • ..) matches zero to many parameters of any type after the annotated parameter.

Finally, the @Before advice advises all methods where all conditions in both pointcuts are satisfied.

The pointcut works with both AspectJ and Spring AOP!

When it comes to performance. The overhead is small, especially with AspectJ that does the weaving on compile-time or load-time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!