0
0
SpringbootConceptBeginner · 3 min read

What is Pointcut in Spring AOP: Definition and Example

In Spring AOP, a pointcut defines where advice (extra behavior) should be applied by specifying join points like method executions. It acts like a filter to select specific methods or classes where the aspect logic runs.
⚙️

How It Works

Think of a pointcut as a precise selector that tells Spring AOP exactly where to insert extra code, called advice, in your application. Imagine you want to add a security check or logging only when certain methods run. The pointcut acts like a spotlight that highlights those methods.

It works by matching method names, annotations, or class types to decide which join points (places in code) should trigger the advice. This way, you keep your main code clean and add extra behavior only where needed, like adding a reminder only on specific calendar events.

💻

Example

This example shows a pointcut that matches all methods in a service class, applying logging advice before method execution.

java
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    @Pointcut("execution(* com.example.service.*.*(..))")
    public void serviceMethods() {}

    @Before("serviceMethods()")
    public void logBefore() {
        System.out.println("Method in service is about to run");
    }
}
Output
Method in service is about to run
🎯

When to Use

Use pointcuts when you want to add common behavior across many parts of your app without changing each method. For example, logging, security checks, transaction management, or performance monitoring.

This helps keep your code simple and focused on business logic, while cross-cutting concerns are handled separately and cleanly.

Key Points

  • A pointcut defines where advice applies by selecting join points.
  • It uses expressions to match methods by name, parameters, or annotations.
  • Pointcuts keep cross-cutting code separate and reusable.
  • They help maintain clean and modular code in Spring applications.

Key Takeaways

A pointcut specifies where advice runs by selecting specific methods or classes.
It uses expressions to match join points like method executions.
Pointcuts help separate cross-cutting concerns from business logic.
They make your code cleaner and easier to maintain in Spring AOP.