Ayush F.’s Post

Self Invocation bypasses Proxy Saw a few posts about this recently, here's what I got in my reading. 🔹 Bean Management All beans in Spring are managed by DefaultListableBeanFactory, which extends DefaultSingletonBeanRegistry. The DefaultSingletonBeanRegistry is the one that actually stores the bean instances — a map of bean name → object reference. 🔹 What Happens with Proxies When we use annotations like @Transactional or @Async, Spring doesn’t just enhance the bean. It creates a proxy (often a CGLIB subclass) and registers that proxy in the registry instead of the original instance. So when another bean calls it, the call goes like: Caller → BeanFactory → Proxy → Actual Bean The proxy gets the call, applies the advice (transaction, async, etc.), and then runs the actual method. 🔹 Why Self Invocation Breaks It When a method calls another method inside the same bean: method1() { method2(); // self-invocation } …the JVM doesn’t go through the registry again. The .class file already contains the direct bytecode reference for method2(). So the call becomes: this.method2() → skips proxy → advice never triggered 🔹 How to Fix It Use AspectJ instead of proxy-based AOP. AspectJ does bytecode weaving, literally modifying the .class file so advice logic is embedded — no proxy needed. Whether you actually need AspectJ is a separate decision — most of the time, the default proxy setup is good enough. #Spring #Java #AOP #Transactional #Async

To view or add a comment, sign in

Explore content categories