Understanding Spring AOP Proxy Creation and Common Pitfalls

This article explains how Spring AOP weaves aspect code using dynamic proxies, why internal calls via this bypass proxy logic, and how to correctly configure and obtain proxied beans using JDK/CGLIB proxies, @EnableAspectJAutoProxy, @Autowired injection, and AopContext.

Top Architect
Top Architect
Top Architect
Understanding Spring AOP Proxy Creation and Common Pitfalls

Spring AOP weaves aspect code into bean methods at runtime, effectively using the proxy pattern.

The article shows a case where a CouponService class's deposit() method is not intercepted because internal calls via this bypass the proxy.

It explains that Spring creates proxies either with JDK dynamic proxies (interface‑based) or CGLIB subclass proxies, and that only beans obtained from the container are proxied.

The core component AnnotationAwareAspectJAutoProxyCreator (a BeanPostProcessor) runs after bean initialization, invoking wrapIfNecessary to replace the original bean with a proxy when needed.

To enable proxy creation, @EnableAspectJAutoProxy (or @EnableAspectJAutoProxy(exposeProxy = true)) must be configured, allowing the current proxy to be accessed via AopContext.currentProxy().

Two common solutions are presented: injecting the bean itself with @Autowired so that the injected reference is the proxied instance, or exposing the proxy through AopContext after setting exposeProxy=true.

Finally, the article emphasizes that only objects created by Spring’s dynamic proxy mechanism can benefit from AOP, and shows the necessary configuration changes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaProxyaopspringdependency-injectionaspectjcglib
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.