DEV Community

Phoenix
Phoenix

Posted on

Spring AOP

In Spring AOP, a join point represents a point in program execution where an aspect can be applied, typically a method execution.
A pointcut is an expression that selects specific join points where we want to apply additional behavior(advice).
An advice defines what action should be executed at those selected join points, such as before or after a method call.
An aspect is a combination of pointcut and advice, representing a complete cross-cutting concern like logging or transaction management.

Spring implements AOP using proxy objects, which intercept method calls and apply the defined advice at runtime.

When a Spring application starts, it scans for beans and also detects classes annotated with @aspect.
These aspect classes contain pointcut expressions, which define where the advice should be applied.
Spring then matches these pointcuts against eligible methods in target beans (which are the join points in Spring AOP).
If a match is found, Spring registers this AOP configuration and creates a proxy around the target bean so that the advice can be applied at runtime.

When a method is invoked on the proxied bean, the call is intercepted by the proxy.
The proxy checks if the method matches any pointcut expressions, and if so, executes the corresponding advice.
After applying the advice, the proxy delegates the call to the actual method in the target object.

Application Startup:

  1. Scan beans
  2. Detect @aspect classes
  3. Read pointcuts and advice
  4. Match pointcuts with target bean methods
  5. Create proxy for matching beans

Runtime:

  1. Method call → goes to proxy
  2. Proxy intercepts
  3. Executes advice
  4. Calls actual method

How does AOP work using @aspect in Spring?

In Spring AOP, when we define a class with @aspect, Spring treats it as a container for cross-cutting concerns.
During application startup, Spring scans these aspects and creates proxy objects for the target beans.
When a method is invoked on the target bean, the call goes through the proxy instead of directly to the object.
The proxy intercepts the method call, checks if any pointcut expressions match, and if so, executes the corresponding advice such as @Before, @After, or @Around.
After applying the advice, the proxy delegates the call to the actual target method.

This proxy-based mechanism allows Spring to add behavior like logging, transactions, or async execution without modifying the actual business logic.

For example, if I define a @Before advice on all service methods, whenever a service method is called, the proxy will first execute the logging logic and then call the actual method.

Scan → Create Proxy → Intercept → Match Pointcut → Execute Advice → Call Method

Spring AOP works by creating proxy objects that intercept method calls, apply advice based on pointcut matching, and then delegate execution to the target object.

Top comments (0)