Cheatsheet
AOP: concepts and pointcuts
Key idea
Aspect-oriented programming separates cross-cutting concerns (auditing, security, transactions, metrics) from business code. An aspect says what to do (advice) and where (pointcut); Spring AOP applies it at runtime by wrapping beans in proxies.
Diagram (UML)
classDiagram
direction LR
class BookingController {
<<client>>
}
class BookingServiceProxy {
<<proxy CGLIB>>
+book(athlete, wod)
}
class BookingService {
<<target>>
+book(athlete, wod)
+bookBoth(athlete, a, b)
}
class AuditAspect {
<<@Aspect @Component>>
+audit(JoinPoint) @Before
}
class BoxPointcuts {
<<pointcuts>>
+serviceLayer() execution(public * ..service.*Service.*(..))
+tracked() @annotation(Tracked)
}
BookingController --> BookingServiceProxy : calls
BookingServiceProxy --|> BookingService : subclass
BookingServiceProxy ..> AuditAspect : runs advice
BookingServiceProxy --> BookingService : delegates
AuditAspect ..> BoxPointcuts : usesKey pieces
@Aspect+@Component: the class holding advice (without@Componentthe scan doesn't find it)@EnableAspectJAutoProxy: enables aspects in plain Spring; Spring Boot does it on its own@Pointcut("expression")on an empty method: a reusable named pointcut- Designators:
execution,within,@annotation,args,bean,this,target,@within JoinPoint: gives access togetSignature(),getArgs(),getTarget(),getThis()
AopConfig.java
@Configuration
@EnableAspectJAutoProxy // plain Spring: turn on @Aspect processing (Spring Boot does it for you)
@ComponentScan(basePackages = {"com.spring2learn.box.aop.service", "com.spring2learn.box.aop.aspect"})
public class AopConfig {
}Remember for the exam
- Vocabulary: join point (an execution point, in Spring always a method execution), pointcut (expression choosing join points), advice (the code that runs), aspect (pointcut + advice), target (real object), proxy (wrapper), weaving (applying aspects)
- Spring AOP weaves at runtime with proxies; full AspectJ can weave at compile or load time
execution([modifiers] returnType [type.]method(params) [throws]):*= anything in one segment;..= any number of parameters or subpackages- Pointcuts are combined with
&&,||and! - With an interface, plain Spring creates a JDK proxy (implements the interfaces); without one, CGLIB (subclass). Spring Boot always uses CGLIB by default
Exam traps
- Internal calls (
this.method()) don't go through the proxy: the advice doesn't run privateorfinalmethods (andfinalclasses with CGLIB) can't be intercepted- With a JDK proxy the bean isn't of the concrete class:
getBean(MembershipService.class)fails; ask for it by interface @Aspectisn't a stereotype: without@Component(or a@Bean) the aspect doesn't exist- Spring AOP only intercepts Spring beans; an object created with
newhas no proxy