AspectJ

AspectJ was created at Xerox PARC by Gregor Kiczales and his team in the late 1990s, and is now part of the Eclipse project. It adds a few constructs to Java (aspect, pointcut and advice) that let you write a concern such as logging once and apply it to many places.

Paradigm: Aspect-Oriented Programming

What Makes AspectJ Special

  • Pointcuts select join points. execution(* Account.deposit(..)) matches every execution of that method, and pointcuts combine with &&, || and !.
  • Advice runs at the join point. before, after, after returning, after throwing and around advice run code at matched points. around can even replace the call.
  • Weaving. The ajc compiler (or a load-time weaver) inserts the advice into the bytecode, so there is no proxy and little runtime cost.
  • Full power. Pointcuts can match field access, constructors and static initializers, not just calls, and aspects can add fields and methods to classes (inter-type declarations).
  • Plain Java syntax. Aspects can also be written as annotated Java classes (@Aspect), which is the style Spring AOP reuses.

Example: Logging every money operation

// Account.java: plain business code, no logging
public class Account {
    private int balance;
    public void deposit(int amount)  { balance += amount; }
    public void withdraw(int amount) { balance -= amount; }
}

// Logging.aj: the cross-cutting concern, written once
public aspect Logging {
    pointcut moneyOps():
        execution(* Account.deposit(..)) ||
        execution(* Account.withdraw(..));

    before(): moneyOps() {
        System.out.println("-> " + thisJoinPoint.getSignature());
    }

    after() returning: moneyOps() {
        System.out.println("<- " + thisJoinPoint.getSignature());
    }
}

How It Works

  • Account knows nothing about logging. It stays short and focused on the business rule.
  • The named pointcut moneyOps() selects the executions of deposit and withdraw. Adding a third method means editing one pointcut.
  • before() advice prints the signature on entry, and after() returning prints it on normal exit. thisJoinPoint gives access to the call.
  • Compiling with ajc weaves the advice in, so account.deposit(50) prints -> void Account.deposit(int) and then <- void Account.deposit(int).

History and Where It Is Used

AspectJ is used for logging, tracing, security checks, transaction boundaries, profiling and enforcing architecture rules. It is also a research platform for AOP. Most teams use its pointcut language indirectly through Spring. See the demo in Demo 10.

Learn More