AspectJ: Aspect-Oriented Programming

Harry · 11 Sep 2026 · 8 views

What is AspectJ?

AspectJ extends Java with aspect-oriented programming (AOP): code that cross-cuts many classes - logging, security checks, transactions, performance timing - lives in one place called an aspect, instead of being duplicated in every method.

AspectJ overview

Setup

In Eclipse, install the AspectJ Development Tools (AJDT) and create an AspectJ project, or add the AspectJ runtime JAR to a normal project.

Adding an Aspect to the AspectJ project

An Aspect With @Aspect Annotations

import org.aspectj.lang.annotation.*;
import org.aspectj.lang.JoinPoint;

@Aspect
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")  // intelligent spring boot
    public void logEntry(JoinPoint jp) {
        System.out.println("ENTER: " + jp.getSignature().getName());
    }

    @AfterReturning(pointcut = "execution(* com.example.service.*.*(..))",
                    returning = "result")
    public void logResult(JoinPoint jp, Object result) {
        System.out.println("RETURN: " + result);
    }

    @Around("execution(* com.example.PaymentService.pay(..))")
    public Object measure(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object out = pjp.proceed();
        System.out.println("took " + (System.currentTimeMillis() - start) + " ms");
        return out;
    }
}

The pointcut execution(* com.example.service.*.*(..)) matches method executions in the service package.

A normal class in the AspectJ project

Every advised method prints its entry/return automatically - with no changes to the target classes.

Aspect output without annotation advice

Key Points

  • @Before, @AfterReturning, @Around are the main advice types.
  • Pointcut expressions select where advice runs.
  • Spring AOP uses AspectJ annotations, so the concept carries over to Spring Boot.
Share this post:

Comments (0)

Please login or register to comment.