Search code examples
javaspringannotationspointcut

Wildcard in @Pointcut annotation in Spring


is it possible to define a Method Pointcut Expression with Annotation wildcards?

For example "Match for all annotations starting with 'Has'"

tried: @Pointcut("execution(@Has.* * *(*))") @Pointcut("execution(@Has..* * *(*))")

but that's not working.

@Pointcut("execution(@HasSpecificAnnoation * *(*))") works for one specific extension. But that's not the thing I need...


Solution

  • There are multiple potential problems in your pointcuts:

    1. Expression *(*) only matches methods with exactly one parameter. Better use *(..) to match any number of parameters.

    2. Expression @Has.* matches any annotation in a package named Has, because . is a package or inner class separator. This is not what you want.

    3. Expression @Has..* matches any annotation in a package named Has or any of its subpackages , because the .. double-dot expression is meant to specifically include subpackages. This is not what you want either.

    What you probably want is to match any method annotated by any annotation in any package with a name starting with Has. The correct syntax is

    execution(@*..Has* * *(..))
    

    where *.. matches all packages and Has* matches the beginning of the annotation type name.

    BTW, if you also want to match those annotations on types and not just on methods, the pointcut would need to be amended as follows (please note the parentheses around the annotated type name:

    execution(@*..Has* * *(..))           // match annotated methods, same as above
      || execution(* (@*..Has* *).*(..))  // match annotated types