Hard👤 8-15 years 2 min read

Dynamic Proxy — Interview Questions

Asked inAmazonMicrosoftOracleGoogle
#dynamic proxy#invocationhandler#aop#spring#cglib
Report issue

⚡ Short Answer

A dynamic proxy is a class generated at runtime that implements one or more interfaces and routes every method call to a single InvocationHandler.invoke(). That handler can add behaviour — logging, timing, transactions, security — before/after delegating to the real object. JDK proxies work on interfaces; CGLIB/ByteBuddy subclass concrete classes. It's the mechanism behind Spring AOP, @Transactional, and mock libraries.

Coffee Chat Question

Concept Made Simple

How do Java dynamic proxies work, and how do frameworks use them for AOP?

🧠Mind Map Answer

Remember It Faster

A proxy is a stand-in that looks like the real interface but funnels every call through your invoke() method, so you can wrap cross-cutting behaviour around the real target without editing it.

JDK proxyProxy.newProxyInstance — interfaces only
HandlerInvocationHandler.invoke(proxy, method, args)
CGLIB/ByteBuddySubclass concrete classes (no interface)
PowersSpring AOP, @Transactional, mocks

Spring wraps your bean in a proxy: calling save() actually hits the proxy, which opens a transaction, calls the real save(), then commits or rolls back — all without a line of transaction code in your method.

Key takeaway: proxies add behaviour around method calls at runtime. JDK = interfaces via InvocationHandler; CGLIB = subclassing — and self-invocation inside a bean bypasses the proxy.

⌨️Hands-on Keyboard

Learn by Doing

java
interface Repo { void save(String s); }

Repo real = s -> System.out.println("saved " + s);

Repo proxy = (Repo) Proxy.newProxyInstance(
    Repo.class.getClassLoader(),
    new Class<?>[]{ Repo.class },
    (p, method, args) -> {                       // InvocationHandler
        System.out.println("BEGIN tx");
        Object r = method.invoke(real, args);     // delegate
        System.out.println("COMMIT tx");
        return r;
    });

proxy.save("order-1");
Output
BEGIN tx
saved order-1
COMMIT tx

🔥What If?

Think Beyond the Expected

Why does calling one @Transactional method from another method in the same bean skip the transaction?

Because the proxy only intercepts calls that come through it from outside. An internal `this.otherMethod()` call goes straight to the target object, bypassing the proxy wrapper entirely — so the advice (transaction, cache, retry) never runs. This 'self-invocation' gotcha is why Spring's proxy-based AOP can silently skip @Transactional/@Cacheable on internal calls; you fix it by refactoring into a separate bean, self-injecting the proxy, or switching to AspectJ weaving.

😂Real World

Spring's @Transactional, @Cacheable, @Async, @Retryable, and security checks are all proxy-based advice; Mockito generates proxies for mocks; mapping and RPC libraries proxy interfaces to turn method calls into network requests. The self-invocation gotcha is one of the most common 'why didn't my transaction roll back?' bugs in real Spring apps.

🎯Interviewer's Expectation

Keywords they're listening for:

runtime-generated proxy over interfacesInvocationHandler.invoke intercepts callsJDK (interface) vs CGLIB (subclass)powers Spring AOP/@Transactionalself-invocation bypasses the proxy

⚠️Common Mistakes

  • Expecting @Transactional to apply on self-invocation
  • Trying to JDK-proxy a class with no interface
  • Forgetting CGLIB can't subclass final classes/methods

Best Practices

  • Program to interfaces so JDK proxies apply cleanly
  • Avoid self-invocation for proxied cross-cutting concerns
  • Use AspectJ weaving when proxy limits get in the way

🔁Follow-up Questions

  • 1JDK dynamic proxy vs CGLIB — when is each used?
  • 2How does reflection enable dynamic proxies?
  • 3Why can't CGLIB proxy a final class or method?

🧩Related Technologies

Spring AOPCGLIBByteBuddyMockito

Continue Learning with AI

Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.

Plain-language foundations

I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner.

Topic: Dynamic Proxy (Advanced Java)
Interview question: "How do Java dynamic proxies work, and how do frameworks use them for AOP?"

Please:
1. Explain the core idea in simple, plain language, using an everyday analogy.
2. Define any technical terms you use.
3. Walk through one small, concrete example.
4. Finish with a single sentence I can easily remember.

Keep the tone friendly and assume I'm new to this topic.
Open inChatGPTGeminiClaude

Was this answer helpful?

Support our platform by exploring our recommended products.

As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.

Related Questions