Careeroza
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.
| Term | Meaning | ShopEase example |
|---|---|---|
| Aspect | a class holding cross-cutting logic | LoggingAspect |
| Join point | a point where advice can run (in Spring: a method call) | OrderService.placeOrder() |
| Pointcut | an expression that selects join points | all methods in ..service..* |
| Advice | the code that runs and when (before, after, around) | log and time the call |
| Target | the real object being advised | the OrderService bean |
| Proxy | object Spring creates around the target | OrderService$$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.