Skip to lesson

Dynamic proxies and how Spring AOP uses them

ShopLite wants timing and logging around many service classes. Writing a proxy class by hand for every interface is repetitive. Can Java generate the proxy for you?

java.lang.reflect.Proxy and InvocationHandler

A dynamic proxy is a proxy class that Java generates while the program runs, instead of one written by hand.

Proxy.newProxyInstance(loader, interfaces, handler) creates an object that implements the given interfaces. Example 1 sends every call on a PaymentGateway to one logging handler.

Example 1 · A logging dynamic proxy for PaymentGateway

DynamicProxyDemo.javaJava
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.util.Arrays;
record PaymentResult(boolean success, String message) {}
interface PaymentGateway {    PaymentResult pay(String orderId, int rupees);    PaymentResult refund(String orderId, int rupees);}
class PayNowGateway implements PaymentGateway {    public PaymentResult pay(String orderId, int rupees) {        System.out.println("  bank: charged Rs " + rupees);        return new PaymentResult(true, "paid");    }
    public PaymentResult refund(String orderId, int rupees) {        System.out.println("  bank: refunded Rs " + rupees);        return new PaymentResult(true, "refunded");    }}
class LoggingHandler implements InvocationHandler {    private final Object target;
    LoggingHandler(Object target) {        this.target = target;    }
    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("[log] " + method.getName() + Arrays.toString(args));        Object result = method.invoke(target, args);           // call the real object        System.out.println("[log] " + method.getName() + " -> " + result);        return result;    }}
public class DynamicProxyDemo {    public static void main(String[] args) {        PaymentGateway real = new PayNowGateway();        PaymentGateway gateway = (PaymentGateway) Proxy.newProxyInstance(                PaymentGateway.class.getClassLoader(),                new Class<?>[] {PaymentGateway.class},                new LoggingHandler(real));
        gateway.pay("A101", 1499);        gateway.refund("A101", 1499);        System.out.println("Generated proxy class: " + Proxy.isProxyClass(gateway.getClass()));    }}
Output
[log] pay[A101, 1499]
  bank: charged Rs 1499
[log] pay -> PaymentResult[success=true, message=paid]
[log] refund[A101, 1499]
  bank: refunded Rs 1499
[log] refund -> PaymentResult[success=true, message=refunded]
Generated proxy class: true

What this code does

  • No class in this file implements logging for pay or refund separately. Java generated a class that implements PaymentGateway and sends both calls to LoggingHandler.invoke.
  • method.getName() and args describe the call, and method.invoke(target, args) runs the same method on the real gateway. The handler would work unchanged for any other interface.

Every call on the generated object goes to one method, InvocationHandler.invoke(proxy, method, args). Inside it you get the called method as a Method object and its arguments as an Object[], do work before and after, and call the real object with method.invoke(target, args).

This is reflection: code that looks at and calls methods by their description instead of by name in the source.

Order of execution

Follow one call through a proxy

Put the steps in the order they happen.

A timing proxy generated for any interface

An InvocationHandler is the one method, invoke(proxy, method, args), that every call on a dynamic proxy reaches.

One handler can serve every interface, because it never names a method. Example 2 writes a generic timed(target, type, clock) helper and uses it on two unrelated interfaces.

Example 2 · timed(): one handler, any interface

TimingProxyDemo.javaJava
import java.lang.reflect.InvocationHandler;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Proxy;import java.util.function.LongSupplier;
interface PaymentGateway {    String pay(String orderId, int rupees);}
interface NotificationService {    void send(String phone, String message);}
class PayNowGateway implements PaymentGateway {    public String pay(String orderId, int rupees) {        return "paid " + orderId;    }}
class SmsService implements NotificationService {    public void send(String phone, String message) {        if (phone.length() != 10) {            throw new IllegalArgumentException("bad phone number: " + phone);        }        System.out.println("  SMS to " + phone + ": " + message);    }}
public class TimingProxyDemo {    static <T> T timed(T target, Class<T> type, LongSupplier clock) {        InvocationHandler handler = (proxy, method, args) -> {            long start = clock.getAsLong();            try {                return method.invoke(target, args);            } catch (InvocationTargetException e) {                throw e.getCause();                   // rethrow the real exception            } finally {                long ms = clock.getAsLong() - start;                System.out.println("[time] " + type.getSimpleName() + "." + method.getName() + " " + ms + " ms");            }        };        return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, handler));    }
    public static void main(String[] args) {        long[] now = {0};        LongSupplier clock = () -> now[0] += 25;      // fake clock: 25 ms per read
        PaymentGateway gateway = timed(new PayNowGateway(), PaymentGateway.class, clock);        NotificationService sms = timed(new SmsService(), NotificationService.class, clock);
        System.out.println(gateway.pay("A101", 1499));        sms.send("9811100001", "Order A101 confirmed");        try {            sms.send("98111", "Order A102 confirmed");        } catch (IllegalArgumentException e) {            System.out.println("Caught: " + e.getMessage());        }    }}
Output
[time] PaymentGateway.pay 25 ms
paid A101
  SMS to 9811100001: Order A101 confirmed
[time] NotificationService.send 25 ms
[time] NotificationService.send 25 ms
Caught: bad phone number: 98111

What this code does

  • The same timed method made proxies for two unrelated interfaces. type.cast gives back a T, so no cast is needed at the call site.
  • The bad phone number throws inside SmsService. Because the handler unwraps InvocationTargetException, the caller catches the original IllegalArgumentException, and finally still prints the timing.

One detail matters. When the real method throws, method.invoke wraps the exception in an InvocationTargetException. The handler must unwrap it with getCause() and throw the original, or the caller receives a confusing UndeclaredThrowableException instead.

Fix the error

Fix the exception handling

The caller sees the wrong exception. Pick the replacement for the highlighted line.

The real service throws IllegalArgumentException, but the caller receives something else.

(proxy, method, args) -> {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw e;
}
}

Error

Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
Caused by: java.lang.reflect.InvocationTargetException

Spring AOP: advice wrapped around bean methods

An aspect is a cross-cutting job written once; advice is the code that runs around a method; a pointcut is the rule that picks which methods get it.

In Spring you write the same job as an @Around method. Example 3 times every method of OrderService with one aspect.

Example 3 · A Spring timing aspect around OrderService

Runs in: a Spring Boot project

TimingAspect.javaJava
// TimingAspect.javapackage com.shoplite.common;
import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Component;
@Aspect@Componentpublic class TimingAspect {
    @Around("execution(* com.shoplite.order.OrderService.*(..))")   // pointcut    public Object time(ProceedingJoinPoint call) throws Throwable {  // advice        long start = System.nanoTime();        try {            return call.proceed();        } finally {            long ms = (System.nanoTime() - start) / 1_000_000;            System.out.println("[timing] " + call.getSignature().toShortString() + " took " + ms + " ms");        }    }}
package com.shoplite.order;
import org.springframework.stereotype.Service;
@Servicepublic class OrderService {    public String placeOrder(String orderId) {        return "Order " + orderId + " placed";    }}
Sample output
[timing] OrderService.placeOrder(..) took 3 ms
Order A101 placed

What this code does

  • @Around advice is the Spring version of the invoke handler: call.proceed() plays the part of method.invoke(target, args). The pointcut expression picks every method of OrderService.
  • A controller that has OrderService injected actually holds a proxy, so placeOrder runs inside time. The number of milliseconds differs on every run.

AOP (aspect-oriented programming) means writing a cross-cutting job such as timing, transactions or security once and applying it to many methods. Spring does this with proxies: when a bean matches a pointcut, the container stores a proxy in place of the bean, and other beans receive that proxy.

@Transactional, @Cacheable, @Async and @PreAuthorize all work this way, so their rules are also proxy rules.

Aspects need Spring's AOP and AspectJ support on the classpath of a Spring Boot project. The example is not a single-file program.

JDK proxies vs CGLIB subclass proxies

A CGLIB proxy is a subclass of your class that a library generates at runtime. It needs no interface but cannot override final methods.

A JDK proxy can only implement interfaces. Example 4 shows it refusing a class, then a simplified subclass proxy that cannot override a final method.

Example 4 · JDK proxies need interfaces; subclass proxies skip final methods

ProxyKindsDemo.javaJava
import java.lang.reflect.Proxy;
class CardGateway {                                       // a class with no interface    public String pay(String orderId) {        return "card paid " + orderId;    }
    public final String receipt(String orderId) {        return "receipt for " + orderId;    }}
// Hand-written stand-in for what CGLIB generates: a subclass that overrides methodsclass CardGatewaySubclassProxy extends CardGateway {    @Override    public String pay(String orderId) {        System.out.println("[proxy] before pay");        return super.pay(orderId);    }    // receipt() is final, so it cannot be overridden here and is never intercepted}
public class ProxyKindsDemo {    public static void main(String[] args) {        try {            Proxy.newProxyInstance(CardGateway.class.getClassLoader(),                    new Class<?>[] {CardGateway.class}, (proxy, method, a) -> null);        } catch (IllegalArgumentException e) {            System.out.println("JDK proxy failed: " + e.getMessage());        }
        CardGateway gateway = new CardGatewaySubclassProxy();        System.out.println(gateway.pay("A101"));        System.out.println(gateway.receipt("A101"));    }}
Output
JDK proxy failed: CardGateway is not an interface
[proxy] before pay
card paid A101
receipt for A101

What this code does

  • Proxy.newProxyInstance accepts only interfaces, so it refuses the class CardGateway.
  • This is a simplified model of a CGLIB proxy: a subclass that overrides each method. pay is intercepted, but the final method receipt runs with no [proxy] line, because a subclass cannot override it.

A JDK dynamic proxy throws IllegalArgumentException when asked to proxy a class, so callers must use the interface type.

CGLIB (built into Spring) generates a subclass at runtime and overrides its methods. It works without interfaces, but a subclass cannot override final methods or extend a final class, so those are never intercepted. Spring Boot uses CGLIB proxies by default, even for beans that implement interfaces.

Self-invocation: why this.method() skips the proxy

Self-invocation is a bean calling its own method through this. The call skips the proxy, so advice such as @Transactional does not run.

A call from another bean goes through the proxy, but this.auditLog() inside the bean goes straight to the bean itself, so no advice runs.

OrderService.javaJava
@Servicepublic class OrderService {    public void placeOrder(Order order) {        saveOrder(order);        auditLog(order);              // this.auditLog(): no proxy, so no new transaction    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)    public void auditLog(Order order) {        // insert an audit row in its own transaction (only when called through the proxy)    }}

Example 5 · Self-invocation: the inner call skips the proxy

SelfInvocationDemo.javaJava
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Proxy;
interface OrderService {    void placeOrder(String id);    void sendConfirmation(String id);}
class SimpleOrderService implements OrderService {    public void placeOrder(String id) {        System.out.println("  saving order " + id);        sendConfirmation(id);                 // same as this.sendConfirmation(id)    }
    public void sendConfirmation(String id) {        System.out.println("  SMS: order " + id + " confirmed");    }}
public class SelfInvocationDemo {    static <T> T logged(T target, Class<T> type) {        return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type},                (proxy, method, args) -> {                    System.out.println("[proxy] " + method.getName());                    try {                        return method.invoke(target, args);                    } catch (InvocationTargetException e) {                        throw e.getCause();                    }                }));    }
    public static void main(String[] args) {        OrderService service = logged(new SimpleOrderService(), OrderService.class);        service.placeOrder("A101");        System.out.println("Calling sendConfirmation from outside:");        service.sendConfirmation("A102");    }}
Output
[proxy] placeOrder
  saving order A101
  SMS: order A101 confirmed
Calling sendConfirmation from outside:
[proxy] sendConfirmation
  SMS: order A102 confirmed

What this code does

  • placeOrder came through the proxy, so it was logged. Inside it, sendConfirmation(id) is a call on this, the real object, so the proxy never saw it.
  • The same method called from outside, through the proxy, is logged. In Spring this is why @Transactional or @Async on a method has no effect when another method of the same bean calls it.

Example 6 · The fix: move the method to another proxied object

SelfInvocationFixDemo.javaJava
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Proxy;
interface NotificationService {    void sendConfirmation(String id);}
interface OrderService {    void placeOrder(String id);}
class SmsNotificationService implements NotificationService {    public void sendConfirmation(String id) {        System.out.println("  SMS: order " + id + " confirmed");    }}
class SimpleOrderService implements OrderService {    private final NotificationService notifier;      // injected: this is a proxy
    SimpleOrderService(NotificationService notifier) {        this.notifier = notifier;    }
    public void placeOrder(String id) {        System.out.println("  saving order " + id);        notifier.sendConfirmation(id);               // goes through the proxy    }}
public class SelfInvocationFixDemo {    static <T> T logged(T target, Class<T> type) {        return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type},                (proxy, method, args) -> {                    System.out.println("[proxy] " + type.getSimpleName() + "." + method.getName());                    try {                        return method.invoke(target, args);                    } catch (InvocationTargetException e) {                        throw e.getCause();                    }                }));    }
    public static void main(String[] args) {        NotificationService notifier = logged(new SmsNotificationService(), NotificationService.class);        OrderService orders = logged(new SimpleOrderService(notifier), OrderService.class);        orders.placeOrder("A101");    }}
Output
[proxy] OrderService.placeOrder
  saving order A101
[proxy] NotificationService.sendConfirmation
  SMS: order A101 confirmed

What this code does

  • The confirmation now lives in its own class, and SimpleOrderService receives it through the constructor. The object it receives is the proxy, so the inner call is logged.
  • This is what a Spring container does when it injects one bean into another: the field holds the other bean's proxy. Splitting the class also gives notification its own clear job.

The proxy never sees an inner call, so there is no timing, no new transaction and no security check. The usual fix is to move the inner method to another bean and inject that bean, so the call goes through its proxy.

Calling the method through an injected reference to your own proxy also works, but it hides the problem.

Predict the output

Does the proxy see the call?

A logging proxy prints one [proxy] line for every call that reaches it.

Round 1 of 2

A controller calls a method on the proxied service.

OrderService service = logged(new SimpleOrderService(), OrderService.class);
service.sendConfirmation("A1");

Next step

Check your understanding

12 quick questions