AOP Concepts

The Problem AOP Solves

Logging, timing, security checks, auditing and transactions are needed in many classes. Copy-pasting that code everywhere mixes it with business logic. These are called cross-cutting concerns. AOP lets you write them once and apply them to many methods.

TermMeaningShopEase example
Aspecta class holding cross-cutting logicLoggingAspect
Join pointa point where advice can run (in Spring: a method call)OrderService.placeOrder()
Pointcutan expression that selects join pointsall methods in ..service..*
Advicethe code that runs and when (before, after, around)log and time the call
Targetthe real object being advisedthe OrderService bean
Proxyobject Spring creates around the targetOrderService$$SpringCGLIB$$0

Where You Already Use AOP

  • @Transactional: a proxy opens and commits/rolls back the transaction.
  • @Cacheable: a proxy checks the cache before calling your method.
  • @Async: a proxy submits the call to a thread pool.
  • @PreAuthorize: a proxy checks permissions first (see the Spring Security material).

Setup

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Note: With the AOP starter on the classpath, aspect proxying is enabled automatically. Spring AOP uses AspectJ annotations but only intercepts public method calls on Spring beans that go through the proxy.