Sub topic 3
The proxy pattern: a stand-in that adds behavior
This chapter explains the proxy design pattern and builds one by hand, first as a class you write yourself and then as a JDK dynamic proxy. Spring AOP is built on this mechanism. Understanding it now explains most of the surprising behavior you will meet later.
Prerequisites
This chapter assumes you know the following:
- Core Java: interfaces, inheritance, and lambdas.
- Basic Spring dependency injection: beans,
@Component,@Configuration. - Basic reflection: what a
java.lang.reflect.Methodobject is.
The pattern in one sentence
A proxy is an object that has the same type as another object, called the target. Callers talk to the proxy. The proxy decides what to do around each call, and usually forwards the call to the target.
Because the proxy and the target share a type, the caller cannot tell them apart. That is the whole trick. You can insert behavior between a caller and a bean without changing either one.
The pattern has three roles:
| Role | Responsibility |
|---|---|
| Subject | The shared type, often an interface, that callers depend on. |
| Target | The real object that does the business work. |
| Proxy | A stand-in with the same type that adds behavior and delegates to the target. |
Common uses
A proxy is useful when you want to control or decorate access to an object. Typical reasons:
- Logging and timing calls.
- Security checks before a call is allowed.
- Lazy loading, where the real object is created only on first use.
- Remote access, where the proxy hides a network call.
- Transactions, where the proxy opens and closes a transaction around the call.
Spring uses the last three kinds of behavior in many places. In every case the business class stays free of that code.
A hand-written proxy
Writing a proxy by hand shows the idea without any framework. The proxy implements the same interface as the target and holds a reference to it.
interface GreetingService {
String greet(String name);
}
class GreetingServiceImpl implements GreetingService {
public String greet(String name) {
return "Hello, " + name;
}
}
class LoggingGreetingProxy implements GreetingService {
private final GreetingService target;
LoggingGreetingProxy(GreetingService target) {
this.target = target;
}
public String greet(String name) {
System.out.println("before greet");
return target.greet(name);
}
}
public class HandWrittenProxyDemo {
public static void main(String[] args) {
GreetingService service = new LoggingGreetingProxy(new GreetingServiceImpl());
System.out.println(service.greet("Ada"));
}
}This prints before greet and then Hello, Ada. The caller in main only knows about GreetingService.
The weakness is scale. You need one proxy class per interface, and each proxy repeats the same forwarding code for every method. If you want to log 200 service methods, you write 200 forwarding methods. That is the problem dynamic proxies solve.
A JDK dynamic proxy
The JDK can generate a proxy class at runtime. You supply a single handler that receives every call. This is the mechanism Spring AOP builds on for beans that implement interfaces.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
interface GreetingService {
String greet(String name);
}
class GreetingServiceImpl implements GreetingService {
public String greet(String name) {
return "Hello, " + name;
}
}
public class ProxyDemo {
public static void main(String[] args) {
GreetingService target = new GreetingServiceImpl();
GreetingService proxy = (GreetingService) Proxy.newProxyInstance(
GreetingService.class.getClassLoader(),
new Class<?>[] { GreetingService.class },
(p, method, methodArgs) -> {
System.out.println("before " + method.getName());
try {
return method.invoke(target, methodArgs);
} catch (InvocationTargetException e) {
throw e.getCause();
}
});
System.out.println(proxy.greet("Ada"));
}
}Proxy.newProxyInstance takes three arguments:
- A class loader, used to define the generated class.
- An array of interfaces the proxy must implement.
- An
InvocationHandler, here a lambda. Its three parameters are the proxy itself, theMethodbeing called, and the argument array.
Every call on proxy lands in the lambda. The lambda prints a line, then calls the real method with method.invoke(target, methodArgs). The output is before greet followed by Hello, Ada.
Why unwrap InvocationTargetException
method.invoke wraps any exception thrown by the target in an InvocationTargetException. If the handler lets that escape, the caller sees a reflection exception instead of the business exception. The catch block rethrows the original cause. Without it, a catch (IllegalArgumentException e) in the caller would never match. Spring's own proxy support does this unwrapping for you.
What the proxy is, and what it is not
The generated class implements the listed interfaces. It does not extend GreetingServiceImpl. You can verify this:
import java.lang.reflect.Proxy;
public class ProxyTypeCheck {
public static void main(String[] args) {
Runnable proxy = (Runnable) Proxy.newProxyInstance(
Runnable.class.getClassLoader(),
new Class<?>[] { Runnable.class },
(p, method, methodArgs) -> null);
System.out.println(proxy instanceof Runnable);
System.out.println(Proxy.isProxyClass(proxy.getClass()));
System.out.println(proxy.getClass().getSimpleName().startsWith("$Proxy"));
}
}The first two lines print true. The third prints true on most JDKs, though the generated class name is an implementation detail and you should not depend on it.
Two consequences follow:
- You can cast a JDK proxy to any interface it implements, but not to the target's concrete class. Casting to
GreetingServiceImplthrowsClassCastException. - Only the interface methods pass through the handler. A method that exists on the implementation but not on the interface is invisible to the proxy.
Rules that explain later problems
The proxy pattern has structural limits. Later chapters rely on these four facts.
- Advice only runs when the call goes through the proxy. The proxy sits between the caller and the target. If the target calls its own method through
this, the call goes straight to the target and skips the proxy. - The proxy and the target are two separate objects. Each has its own identity.
proxy == targetis false, and comparing them withequalsor using one as a map key can surprise you. - The proxy's type is limited. A JDK proxy has the interface type only. Spring can also create class-based proxies by subclassing, which have different limits.
- Someone must hand out the proxy. Callers only benefit if they receive the proxy instead of the target. In Spring, the container does this by replacing the bean with its proxy during startup, so injected references point to the proxy.
Exercises
Exercise
A JDK dynamic proxy is created for GreetingService, which is implemented by GreetingServiceImpl. A caller writes GreetingServiceImpl impl = (GreetingServiceImpl) proxy;. What happens, and why?
Show answer
It throws a ClassCastException. The generated proxy class implements GreetingService but does not extend GreetingServiceImpl, so it is not an instance of the implementation class. Callers must use the interface type.
Exercise
In the handler of a JDK dynamic proxy, why is it better to catch InvocationTargetException and throw e.getCause() than to let the exception propagate?
Show answer
Method.invoke wraps any exception from the target in an InvocationTargetException. Letting it propagate hides the real business exception behind a reflection exception, so callers that catch the specific exception type would miss it. Rethrowing the cause preserves the target's real exception.
Exercise
A class Report has a method a() that calls this.b(). A proxy wraps Report and adds logging to every method. When a caller invokes a() on the proxy, how many log entries appear, and why?
Show answer
One, for a(). The call from the caller to a() passes through the proxy. The call from a() to b() uses this, which is the target and not the proxy, so the proxy never sees it.