AdvancedAdvanced Java & Spring Boot · Lesson 17 of 20 · Updated ·
Spring AOP and Proxies — How @Transactional Really Works, and the Self-Invocation Trap
In lesson 8 you put @Transactional on a service method and it simply worked: the method ran inside a database transaction that committed at the end or rolled back on an exception. But your method contains no transaction code. So who begins and commits the transaction? The answer is a proxy, created by Spring AOP. Understanding this one mechanism explains several interview questions at once — and a bug that confuses many developers.
1. The problem AOP solves
Some code is needed in many methods but is not part of their real job: starting and committing transactions, logging, measuring time, checking security, caching. These are called cross-cutting concerns because they cut across every layer.
If you write them by hand, every service method starts with the same five lines and ends with the same five lines. Aspect-Oriented Programming (AOP) lets you write that code once, in an aspect, and tell Spring which methods it applies to.
| Term | Meaning | Example |
|---|---|---|
| Aspect | A class holding cross-cutting code | TimingAspect |
| Join point | A point where an aspect can run; in Spring AOP, always a method call | OrderService.placeOrder() |
| Advice | The code that runs, and when (before, after, around) | "log the time taken" |
| Pointcut | An expression choosing which join points get the advice | all methods in classes named *Service |
| Target | The real object being advised | your OrderService bean |
| Proxy | The wrapper object Spring creates around the target | what other beans actually receive |
2. A proxy, built in plain Java
A proxy is an object that has the same methods as the real object, but does something extra before and after passing each call on. Java can create one at runtime with java.lang.reflect.Proxy. This small program does roughly what Spring does for @Transactional:
// Not compiled: not part of the course projects — a plain-Java demo you can run as Main.java
import java.lang.reflect.*;
interface EnrollmentService {
void enroll(String student, String course);
}
class RealEnrollmentService implements EnrollmentService {
public void enroll(String student, String course) {
if (course.isEmpty()) throw new IllegalArgumentException("no course");
System.out.println(" saving " + student + " -> " + course);
}
}
public class Main {
public static void main(String[] args) {
EnrollmentService target = new RealEnrollmentService();
InvocationHandler tx = (proxy, method, methodArgs) -> {
System.out.println("BEGIN transaction for " + method.getName());
try {
Object result = method.invoke(target, methodArgs); // call the real object
System.out.println("COMMIT");
return result;
} catch (InvocationTargetException e) {
System.out.println("ROLLBACK because " + e.getCause().getMessage());
return null;
}
};
EnrollmentService service = (EnrollmentService) Proxy.newProxyInstance(
EnrollmentService.class.getClassLoader(),
new Class<?>[]{EnrollmentService.class}, tx);
service.enroll("Asha", "Java");
service.enroll("Ravi", "");
System.out.println(service instanceof RealEnrollmentService);
}
}
BEGIN transaction for enroll
saving Asha -> Java
COMMIT
BEGIN transaction for enroll
ROLLBACK because no course
false
The caller only sees an EnrollmentService. It has no idea that a wrapper is adding transaction handling around every call. The last line prints false: the object the caller holds is not the real class at all — it is a generated proxy class that implements the same interface. (To keep the demo short, the handler prints the failure instead of throwing it again; Spring re-throws the exception after rolling back.)
Spring creates proxies in two ways:
| Kind | How it works | Needs |
|---|---|---|
| JDK dynamic proxy | Generates a class that implements the bean's interfaces (like the demo) | The bean must implement an interface |
| CGLIB proxy | Generates a subclass of the bean's class at runtime and overrides its methods | The class and methods must not be final |
Spring Boot uses class-based (CGLIB) proxies by default, so your beans do not need interfaces. Because a subclass cannot override private or final methods, annotations such as @Transactional have no effect on private or final methods.
3. Writing your own aspect
Here is a sketch of an aspect that logs how long every service method takes. It needs the AspectJ starter dependency (spring-boot-starter-aop in Spring Boot 3; renamed spring-boot-starter-aspectj in Spring Boot 4).
// Not compiled: a short sketch of a typical @Around aspect
@Aspect
@Component
public class TimingAspect {
private static final Logger log = LoggerFactory.getLogger(TimingAspect.class);
@Around("execution(* com.skills101.courses..*Service.*(..))")
public Object time(ProceedingJoinPoint call) throws Throwable {
long start = System.nanoTime();
try {
return call.proceed(); // run the real method
} finally {
long ms = (System.nanoTime() - start) / 1_000_000;
log.info("{} took {} ms", call.getSignature().toShortString(), ms);
}
}
}
Read the pointcut execution(* com.skills101.courses..*Service.*(..)) left to right: any return type (*), in package com.skills101.courses or any sub-package (..), any class whose name ends in Service, any method (.*), with any arguments ((..)).
There are five kinds of advice:
@Around is the most powerful: it decides whether to call proceed() at all, can change the arguments or the result, and can catch exceptions. Use the simplest type that does the job.
4. The self-invocation trap
Now the bug. Suppose placeOrder() calls another method of the same class, and that method has its own annotation (for example @Transactional(propagation = Propagation.REQUIRES_NEW) or @Async). The inner annotation does nothing. Here is why, in plain Java:
// Not compiled: not part of the course projects — a plain-Java demo you can run as Main.java
import java.lang.reflect.*;
interface OrderService {
void placeOrder();
void sendReceipt();
}
class RealOrderService implements OrderService {
public void placeOrder() {
System.out.println("placing order");
sendReceipt(); // really this.sendReceipt(): the REAL object
}
public void sendReceipt() {
System.out.println("sending receipt");
}
}
public class Main {
public static void main(String[] args) {
OrderService target = new RealOrderService();
InvocationHandler h = (p, m, a) -> {
System.out.println("[proxy] " + m.getName());
return m.invoke(target, a);
};
OrderService service = (OrderService) Proxy.newProxyInstance(
OrderService.class.getClassLoader(), new Class<?>[]{OrderService.class}, h);
service.placeOrder();
System.out.println("---");
service.sendReceipt();
}
}
[proxy] placeOrder
placing order
sending receipt
---
[proxy] sendReceipt
sending receipt
When the controller calls placeOrder(), the call passes through the proxy ([proxy] placeOrder). Inside the real object, sendReceipt() means this.sendReceipt(), and this is the real object, not the proxy. So no [proxy] sendReceipt line appears — any advice on sendReceipt is skipped. Only a call from outside (after ---) goes through the proxy.
How to fix it:
- Best: move the inner method to a separate bean (for example a
ReceiptService) and inject it. Now the call crosses a bean boundary and goes through that bean's proxy. - Inject the bean into itself (marked
@Lazy) and callself.sendReceipt(). This works but is confusing to read. - Use full AspectJ weaving, which changes the compiled bytecode instead of using proxies. Powerful, but rarely needed.
Common mistakes
- Putting
@Transactional,@Asyncor@Cacheableon aprivatemethod. Proxies cannot intercept it, and nothing warns you. - Calling an annotated method from another method in the same class and expecting the annotation to apply.
- Declaring a bean class or its methods
final— the CGLIB proxy cannot override them. (Kotlin classes are final by default for the same reason.) - Writing a pointcut so wide (
execution(* *(..))) that it advises Spring's own beans and slows everything down. - Forgetting to call
proceed()in an@Aroundadvice — the real method never runs.
Quick recap
- AOP moves cross-cutting code (transactions, logging, security, caching) into aspects.
- Spring AOP works with proxies: other beans receive a wrapper that runs advice around the real method.
- JDK proxies implement interfaces; CGLIB proxies subclass your class (the Spring Boot default).
- Advice types:
@Before,@AfterReturning,@AfterThrowing,@After,@Around. - Calls on
thisskip the proxy, so annotations on the inner method are ignored. Move the method to another bean.