Spring / Spring7 Intermediate to Advanced Interview questions
Explain the internal working of Spring AOP proxy creation?
Spring AOP proxies are created lazily, at bean-instantiation time, by a BeanPostProcessor - specifically a subclass of AbstractAutoProxyCreator - that inspects each new bean against the registered aspects' pointcuts to decide whether it needs advising at all.
flowchart TD
A[Bean instantiated] --> B{Matches any pointcut?}
B -- No --> C[Return plain bean]
B -- Yes --> D{Implements an interface?}
D -- Yes --> E[JDK dynamic proxy]
D -- No, or proxyTargetClass=true --> F[CGLIB subclass proxy]
If the target class implements at least one interface, Spring defaults to a JDK dynamic proxy - a java.lang.reflect.Proxy instance implementing the same interfaces, where every call is routed through an InvocationHandler that first runs the matched advice chain (converted internally into a chain of MethodInterceptors) and then, if appropriate, invokes the real target. If the class implements no interfaces, or proxyTargetClass=true is configured, Spring instead uses CGLIB, generating a runtime subclass of the target class itself that overrides advised methods to insert the same interception logic.
This mechanism explains two well-known constraints: CGLIB-based proxies can't advise final methods (a subclass can't override them) and can't be applied to final classes at all; and advice only ever runs for calls that arrive through the proxy reference the container handed out - a call made directly on this from inside the target class bypasses the proxy and its interception logic entirely, which is exactly why self-invoked @Transactional calls silently skip their transaction.
More Related questions...