DEV Community

Tommy
Tommy

Posted on

Spring AOP - Reusable Pointcut Expressions

Pointcut

A pointcut is a collection of one or more joinpoints where an advice should be invoked. You can declare pointcuts utilizing expressions or patterns like you'll see in the examples below.

Syntax

@Pointcut(" execution(modifiers? return-type declaring-type? method-name(param) throws?) ")

  • the pattern is optional if it has a ? symbol
  • patterns can use wildcards * (matches everything)
  • the @Pointcut annotation contains a set of one or more JoinPoints where an advice should be executed
  • modifiers? (optional) is the method's access modifier like public, protected, private
  • return-type is the method's return type
  • declaring-type? (optional) is the package or class name
  • method-name(param) is the method's name with its parameters
  • param could take zero or more arguments. () matches a method that takes no parameters, whereas (..) matches any number of parameters (zero or more). The pattern (*) matches a method taking one parameter of any type
  • throws? (optional) is the exception type

Combining Pointcut Expressions

You can combine pointcut declarations using:
&&, ||, ! operators

Examples

Declare pointcut methods (must not have a body)

@Pointcut("execution(public * dev.company.*.service.*.get*(..))")
public void pointCutTemplateServiceForGet() {}

@Pointcut("execution(public * dev.company.*.service.*.post*(..))")
public void pointCutTemplateServiceForPost() {}

@Pointcut("execution(public * dev.company.*.service.*.delete*(..))")
public void pointCutTemplateServiceForDelete() {}
Enter fullscreen mode Exit fullscreen mode

Reuse a pointcut
In this example, we use the pointcut template pointCutTemplateServiceForGet() twice for two different advice

@Before("pointCutTemplateServiceForGet()")
// implementation goes here
Enter fullscreen mode Exit fullscreen mode
@After("pointCutTemplateServiceForGet()")
// implementation goes here
Enter fullscreen mode Exit fullscreen mode

Combine multiple pointcuts using &&

@After(pointCutTemplateServiceForGet() && pointCutTemplateServiceForPost())
// implementation goes here
Enter fullscreen mode Exit fullscreen mode

Exclude a pointCut using !

@Before(pointCutTemplateServiceForGet() && !(pointCutTemplateServiceForDelete()))
// implementation goes here
Enter fullscreen mode Exit fullscreen mode

Exclude multiple pointcuts

@Before(pointCutTemplateServiceForDelete() && !(pointCutTemplateServiceForGet() || pointCutTemplateServiceForPost()))
// implementation goes here
Enter fullscreen mode Exit fullscreen mode

There are many more possibilities when mixing and matching pointcut expressions, but I'll leave it up to your imagination.

See this article to learn more about Spring AOP.

Top comments (0)