Tutorials Logic, IN info@tutorialslogic.com

Spring AOP Aspects, Pointcuts, Advice, Weaving

Proxy Interception

Spring AOP applies reusable behavior around method execution through proxies. It is useful for cross-cutting concerns such as transaction boundaries, authorization, metrics, and targeted logging, where the same policy would otherwise be scattered across many services. It is not a replacement for clear domain logic.

After this lesson, you can identify join points matched by a pointcut, choose an advice type, explain the self-invocation limitation, and decide whether an aspect makes a concern clearer or merely hides control flow.

AOP Concepts

Aspect-Oriented Programming (AOP) is a programming paradigm that allows you to separate cross-cutting concerns (like logging, security, transactions) from your business logic. Instead of scattering the same code across many classes, you define it once in an Aspect.

Term Description
Aspect A class containing cross-cutting logic (annotated with @Aspect)
Advice The action taken at a join point (@Before, @After, @Around, etc.)
Join Point A point in program execution (method call, exception throw)
Pointcut An expression that matches join points (which methods to intercept)
Weaving Linking aspects with application objects (Spring does this at runtime)

Logging Aspect with All Advice Types

Logging Aspect with All Advice Types
package com.example.aspect;

import org.aspectj.lang.annotation.*;
import org.aspectj.lang.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    // Pointcut: matches all methods in service package
    @Pointcut("execution(* com.example.service.*.*(..))")
    public void serviceLayer() {}

    // @Before: runs BEFORE the method
    @Before("serviceLayer()")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("[BEFORE] " + joinPoint.getSignature().getName()
                + " called with args: " + java.util.Arrays.toString(joinPoint.getArgs()));
    }

    // @After: runs AFTER the method (regardless of outcome)
    @After("serviceLayer()")
    public void logAfter(JoinPoint joinPoint) {
        System.out.println("[AFTER] " + joinPoint.getSignature().getName() + " completed");
    }

    // @AfterReturning: runs after successful return
    @AfterReturning(pointcut = "serviceLayer()", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        System.out.println("[AFTER_RETURNING] " + joinPoint.getSignature().getName()
                + " returned: " + result);
    }

    // @AfterThrowing: runs when method throws exception
    @AfterThrowing(pointcut = "serviceLayer()", throwing = "ex")
    public void logAfterThrowing(JoinPoint joinPoint, Exception ex) {
        System.err.println("[AFTER_THROWING] " + joinPoint.getSignature().getName()
                + " threw: " + ex.getMessage());
    }

    // @Around: wraps the method - most powerful advice
    @Around("execution(* com.example.service.*.*(..)) && @annotation(com.example.annotation.Timed)")
    public Object measureTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            Object result = joinPoint.proceed(); // Execute the actual method
            long duration = System.currentTimeMillis() - start;
            System.out.println("[TIMED] " + joinPoint.getSignature().getName()
                    + " took " + duration + "ms");
            return result;
        } catch (Exception e) {
            System.err.println("[TIMED] " + joinPoint.getSignature().getName()
                    + " failed after " + (System.currentTimeMillis() - start) + "ms");
            throw e;
        }
    }
}

Pointcut Expressions

Pointcut Expression Examples

Pointcut Expression Examples
@Aspect
@Component
public class PointcutExamples {

    // All methods in UserService
    @Pointcut("execution(* com.example.service.UserService.*(..))")
    public void userServiceMethods() {}

    // All public methods in any class
    @Pointcut("execution(public * *(..))")
    public void publicMethods() {}

    // Methods starting with "get"
    @Pointcut("execution(* com.example..get*(..))")
    public void getterMethods() {}

    // Methods with @Transactional annotation
    @Pointcut("@annotation(org.springframework.transaction.annotation.Transactional)")
    public void transactionalMethods() {}

    // All beans in service package
    @Pointcut("within(com.example.service.*)")
    public void servicePackage() {}

    // Combine pointcuts
    @Pointcut("servicePackage() && publicMethods()")
    public void publicServiceMethods() {}

    // Use combined pointcut
    @Before("publicServiceMethods()")
    public void logPublicServiceCall(JoinPoint jp) {
        System.out.println("Calling: " + jp.getSignature());
    }

    // Transaction aspect example
    @Around("@annotation(com.example.annotation.RequiresTransaction)")
    public Object manageTransaction(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("Starting transaction...");
        try {
            Object result = pjp.proceed();
            System.out.println("Committing transaction...");
            return result;
        } catch (Exception e) {
            System.out.println("Rolling back transaction...");
            throw e;
        }
    }
}

Proxy Boundary

A Spring bean is wrapped by a proxy when an advisor applies. Calls entering through that proxy can be intercepted; a method calling another advised method on this bypasses the proxy, so the second advice does not run. This explains many cases where @Transactional or a custom aspect appears to work from another bean but not from inside the same class.

Design around a meaningful service boundary instead of exposing methods only to satisfy a proxy. Moving the second operation to another focused bean is often clearer. AspectJ weaving can intercept a broader set of join points, but it adds tooling and should be chosen only when proxy-based AOP cannot express the requirement.

Pointcut Precision

A pointcut should describe exactly which operations carry the policy. Broad package wildcards are convenient but can start intercepting new methods silently as the codebase grows. Prefer a narrow package boundary, a purpose-specific annotation, or both, and give the pointcut a name that states the policy.

Use before advice for checks that do not need the result, after-returning advice for successful outcomes, after-throwing advice for failure observation, and around advice only when control over invocation or timing is required. Around advice must call proceed exactly when the target operation should execute and must preserve the return value and exception semantics.

Aspect Verification

Test an aspect through a proxied Spring bean, not by constructing the target with new. Verify both a matching method and a nearby non-matching method so the test catches pointcuts that are too broad. For timing or logging, assert the interaction with a small recorder abstraction rather than brittle console text.

Avoid recording method arguments blindly. Authentication tokens, personal data, and large object graphs can leak into logs or create expensive serialization. Select safe fields deliberately and keep observability failure from changing the business result.

Before you move on

Aspect Fit

4 checks
  • Name the cross-cutting policy before introducing an aspect.
  • Confirm the call enters through a Spring proxy.
  • Keep the pointcut narrow and test one non-match.
  • Preserve return values, exceptions, and sensitive data boundaries.

Proxy Surprises

  • Expecting self-invocation to trigger advice.

    Call through a separate proxied bean or redesign the service boundary.
  • Using around advice for every concern.

    Choose the least powerful advice type that expresses the policy.
  • Logging every argument.

    Record only approved, bounded, non-sensitive fields.

Try this next

Test a Pointcut

0 of 2 completed

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.