Skip to content

Pointcut in Spring AOP

1. Overview

Before we dive into Pointcut in Spring AOP, let’s understand a few AOP terminologies

Join Point: A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, it always represents the method execution.

Advice: An Action to be taken before, after, or around a particular join point or method execution. The different advice types include “around,” “before” and “after” advice.

Pointcut in Spring AOP: A predicate that matches join points. It is a set of one or more join points (method executions) for which the Advice executes.

Pointcut expression: An expression language that helps to match the target methods to apply the advice.

2. Pointcut Declaration

A pointcut declaration contains two parts

  • A pointcut signature comprises a name and parameters if any. It is a regular method definition.
  • A pointcut expression that determines exactly which method executions to match
@Pointcut("execution(* transfer(..))") private void anyOldTransfer() {} 

The above example defines an ‘anyOldTransfer’ pointcut that will match the execution of any method named ‘transfer’. The pointcut expression is passed as a value to the @Pointcut annotation. Due to which this pointcut matches any method with the name ‘transfer’. See Pointcut Expressions for more information.

A pointcut signature must have a void return type. Notice the void return type of the ‘anyOldTransfer’ pointcut method. Below are few examples to help you understand the use of pointcuts.

@After("anyOldTransfer()")
public void afterOldTransfer() {}
@Before("anyOldTransfer()")
public void beforeOldTransfer() {}

The pointcut anyOldTransfer is passed to the @After and @Before annotations. So these After and Before advice methods will execute whenever you invoke the target method named transfer.

3. Pointcut Designators and expressions

A pointcut expression starts with a pointcut designator like execution, within, args, this, target, and so on. See this article Pointcut designator and Pointcut expressions for complete information.

4. Conclusion

In this article, we have learned about Pointcuts, Pointcut designators, and expressions

Leave a Reply

Your email address will not be published. Required fields are marked *