Video in progress

Junior 🌱 Spring

What is AOP, and what problems does it solve in a real project?

AOP is a way to collect "side" logic that repeats across many methods (logging, transactions, security, timing) in one place. The business code stays clean.

📖 Answer

Imagine each of 40 service methods contains this:

long start = System.nanoTime();
try {
    // the main work
} finally {
    log.info("work took {} ms", (System.nanoTime() - start) / 1_000_000);
}

This code has nothing to do with the business, but it's repeated everywhere. With AOP you move it into a single aspect and say with a rule which methods it applies to.

Spring uses AOP itself every day, even if you don't notice:

  • @Transactional: opening and closing the transaction;
  • @Cacheable: reading from the cache;
  • @Async: running on another thread;
  • @PreAuthorize: checking permissions.

Spring AOP works through a proxy: it injects a wrapper in place of the bean, and the wrapper does the extra work before and after the call. That's why it only works on public method calls of Spring beans. On an object created with new, or on a this.method() call inside a class, the aspect doesn't run.