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)

ApplicationContextAthleteBookingControllerBookingService (proxy)30BookingServiceAuditAspectBoxPointcutsAuditLog

Key pieces

  • @Aspect + @Component: the class holding advice (without @Component the 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 to getSignature(), 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
  • private or final methods (and final classes 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
  • @Aspect isn't a stereotype: without @Component (or a @Bean) the aspect doesn't exist
  • Spring AOP only intercepts Spring beans; an object created with new has no proxy

← AOP: concepts and pointcuts · Run it