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.
- In the box
- The audit line was copied into every method of every box service. Move it to an aspect, learn the AOP vocabulary the exam asks about, how to read pointcut expressions, and why a JDK proxy isn't the same as a CGLIB one.
The athlete sends POST booking to the controller, which calls book() on LoggingBookingService, highlighted in red: auditing is mixed with business logic.
Inside the context, the controller, the BookingService proxy and the BookingService target; below, AuditAspect. The proxy and the aspect are highlighted.
AuditAspect, highlighted, sends add() to AuditLog. Above, the controller, proxy and BookingService flow.
BoxPointcuts, highlighted, sends serviceLayer() to AuditAspect: the aspect uses the named pointcut.
BoxPointcuts stays highlighted while the code shows which methods match each expression.
Packets travel along the chain: POST booking to the controller, book() to the proxy, @Before towards AuditAspect and book() from the proxy to the BookingService target.
The bookBoth() packet goes from the proxy to BookingService, highlighted: the internal book() calls stay inside the target.
The controller sends renew() to the JDK proxy, highlighted together with the Renewals interface: the proxy and MembershipService implement Renewals, but the proxy isn't a MembershipService.
Final view: controller, proxy and BookingService on top; AuditAspect with its pointcuts and the AuditLog below.
Step 1 of 9
The same line in every method
Auditing: the box wants to record every operation of its services (who booked, who cancelled, who renewed). The first version adds an audit.add(...) line at the start of every method.
It works, but that line is repeated in book, in cancel, in MembershipService, in PaymentService… and it's mixed with the business logic.
Step 2 of 9
The AOP vocabulary
AOP moves that code somewhere else. Before any code, the vocabulary (it shows up on the exam almost word for word):
- Join point: a point in execution where you can step in. In Spring AOP, always a method execution.
- Pointcut: an expression that chooses join points ("every public method of the services").
- Advice: the code that runs at those points, and when (before, after, around).
- Aspect: the module bringing pointcuts and advice together.
- Target: the real object,
BookingService, which now only has business logic. - Proxy: the object Spring puts in front of the target to run the advice.
- Weaving: the process of applying aspects. Spring does it at runtime, with proxies.
Step 3 of 9
An aspect with @Aspect
AuditAspect is an ordinary class with two annotations:
@Aspect: it holds advice.@Component: it must be a bean.@Aspectis not a stereotype, so without@Component(or a@Bean) the scan doesn't register it.
Its audit(JoinPoint jp) method carries @Before(...): it will run before every method matching the pointcut. The JoinPoint tells it which method (getSignature()) and with which arguments (getArgs()).
Step 4 of 9
Named pointcuts
You can write the expression inside @Before, but it's better to name it with @Pointcut on an empty method and reuse it:
serviceLayer():execution(public * com.spring2learn.box.aop.service.*Service.*(..)).tracked():@annotation(com.spring2learn.box.aop.Tracked), any method with that annotation.serviceCallFor(athlete): combines with&&and binds the first argument withargs(athlete, ..).
Advice refers to them by their full name: @Before("com.spring2learn.box.aop.aspect.BoxPointcuts.serviceLayer()").
Step 5 of 9
Reading an execution expression
The anatomy: execution(modifiers? return declaring-type?.method(params) throws?). Parts marked ? are optional.
*= anything in one segment (a type, a name, a package)...= any number: of parameters in(..), of subpackages incom.box..*.(String, String)requires exactly those parameters;(String)doesn't match a two-parameter method.
Other common designators: within(package..*) (everything in a package), @annotation(Annotation), bean(*Service) (by bean name, Spring only), args(...), this(Type) (the proxy) and target(Type) (the real object).
Step 6 of 9
The request goes through the proxy
Follow POST /api/bookings:
- The controller calls
book()… on the proxy (that's what Spring injected). - The proxy sees that
bookmatchesserviceLayer()and runs the@Before: the line is recorded. - The proxy calls
book()on the target, which returns the booking.
The test confirms the result, the audit line and that the bean is a CGLIB proxy: BookingService implements no interface, so Spring creates a subclass.
Step 7 of 9
Trap: this skips the proxy
bookBoth() calls this.book() twice. From the controller, the proxy intercepts bookBoth() and the advice runs once.
But the two internal calls happen inside the target: this is the real object, not the proxy, so the advice doesn't run for them.
Step 8 of 9
JDK proxy or CGLIB proxy
MembershipService does implement an interface, Renewals. In plain Spring (proxyTargetClass = false, the default of @EnableAspectJAutoProxy):
- With an interface → JDK dynamic proxy: a new object that implements the same interfaces but doesn't extend your class.
- Without one → CGLIB: a subclass of your class.
Consequence: getBean(MembershipService.class) fails (the proxy isn't a MembershipService) and you must ask for it as Renewals. Also, the JoinPoint reports the interface method (Renewals.renew).
Step 9 of 9
Recap
- AOP separates cross-cutting concerns: aspect = pointcut (where) + advice (what and when).
- Spring AOP = runtime proxies, method executions of beans only.
@Aspect+@Component, and@EnableAspectJAutoProxyoutside Boot.execution(...):*one segment,..any number.- Traps:
this,private/final, and JDK proxy (Spring) versus CGLIB (Boot).
Code
LoggingBookingService.java
/** Before: the audit line is copied into every method, mixed with the business logic. */
public class LoggingBookingService {
public final List<String> audit = new ArrayList<>();
public String book(String athlete, String wod) {
audit.add("book(" + athlete + ", " + wod + ")"); // cross-cutting
return athlete + " → " + wod; // the real work
}
public String cancel(String athlete, String wod) {
audit.add("cancel(" + athlete + ", " + wod + ")"); // …again
return athlete + " ✗ " + wod;
}
// … and again in MembershipService, PaymentService, …
}BookingService.java
@Service
public class BookingService { // the target: only business logic, no audit code
public String book(String athlete, String wod) {
return athlete + " → " + wod;
}
public String cancel(String athlete, String wod) {
return athlete + " ✗ " + wod;
}
public String bookBoth(String athlete, String first, String second) {
return this.book(athlete, first) + " | " + this.book(athlete, second); // self-invocation
}
}AuditAspect.java
@Aspect // this class holds advice…
@Component // …and must still be a bean (@Aspect alone is not picked up by the scan)
public class AuditAspect {
private final AuditLog log;
public AuditAspect(AuditLog log) {
this.log = log;
}
@Before("com.spring2learn.box.aop.aspect.BoxPointcuts.serviceLayer()") // WHEN + WHERE
public void audit(JoinPoint jp) { // WHAT
log.add(jp.getSignature().getDeclaringType().getSimpleName() + "." + jp.getSignature().getName()
+ Arrays.toString(jp.getArgs()));
}
@Before("com.spring2learn.box.aop.aspect.BoxPointcuts.tracked()")
public void tracked(JoinPoint jp) {
log.add("tracked:" + jp.getSignature().getName());
}
}BoxPointcuts.java
/** Named pointcuts: WHERE the advice applies. Reusable from any aspect. */
public class BoxPointcuts {
@Pointcut("execution(public * com.spring2learn.box.aop.service.*Service.*(..))")
public void serviceLayer() { } // any public method of a class ending in "Service"
@Pointcut("@annotation(com.spring2learn.box.aop.Tracked)")
public void tracked() { } // any method annotated with @Tracked
@Pointcut("serviceLayer() && args(athlete, ..)")
public void serviceCallFor(String athlete) { } // combined, and binds the first argument
}PointcutExpressionTest.java
@Test
void readingPointcutExpressions() throws Exception {
assertThat(matches("execution(* com.spring2learn.box.aop.service.*.*(..))", BookingService.class, "book")).isTrue();
assertThat(matches("execution(String book*(String, String))", BookingService.class, "book")).isTrue();
assertThat(matches("execution(* cancel(..))", BookingService.class, "book")).isFalse();
assertThat(matches("execution(* *(String))", BookingService.class, "book")).isFalse(); // one String only
assertThat(matches("within(com.spring2learn.box.aop..*)", BookingService.class, "book")).isTrue(); // ".." = subpackages
assertThat(matchesRenew("@annotation(com.spring2learn.box.aop.Tracked)")).isTrue();
assertThat(matches("@annotation(com.spring2learn.box.aop.Tracked)", BookingService.class, "book")).isFalse();
}AspectTest.java
@Test
void theProxyRunsTheAdviceBeforeTheTarget() {
try (var ctx = new AnnotationConfigApplicationContext(AopConfig.class)) {
BookingService bookings = ctx.getBean(BookingService.class);
AuditLog log = ctx.getBean(AuditLog.class);
assertThat(bookings.book("Ana", "Fran")).isEqualTo("Ana → Fran");
assertThat(log.lines()).containsExactly("BookingService.book[Ana, Fran]");
assertThat(AopUtils.isCglibProxy(bookings)).isTrue(); // no interface: CGLIB subclass
}
}AspectTest.java
@Test
void callsThroughThisSkipTheProxy() {
try (var ctx = new AnnotationConfigApplicationContext(AopConfig.class)) {
ctx.getBean(BookingService.class).bookBoth("Ana", "Fran", "Murph");
assertThat(ctx.getBean(AuditLog.class).lines())
.containsExactly("BookingService.bookBoth[Ana, Fran, Murph]"); // the two inner book() calls: not audited
}
}AspectTest.java
@Test
void withAnInterfacePlainSpringBuildsAJdkProxy() {
try (var ctx = new AnnotationConfigApplicationContext(AopConfig.class)) {
Renewals renewals = ctx.getBean(Renewals.class);
assertThat(AopUtils.isJdkDynamicProxy(renewals)).isTrue(); // implements Renewals, not a subclass
assertThatThrownBy(() -> ctx.getBean(MembershipService.class))
.isInstanceOf(NoSuchBeanDefinitionException.class); // the proxy is not a MembershipService
renewals.renew("Leo");
assertThat(ctx.getBean(AuditLog.class).lines())
.containsExactly("Renewals.renew[Leo]", "tracked:renew"); // the JDK proxy reports the interface method
}
}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 {
}