Sub topic 18
Creating proxies by hand with ProxyFactory
This chapter assumes you know the proxy pattern, the difference between JDK dynamic proxies and CGLIB proxies, and the basic AOP vocabulary (advice, pointcut, join point). You should also be comfortable with simple Java lambdas and interfaces.
Why build a proxy yourself
Normally Spring creates proxies for you. A bean post-processor sees a bean that matches an aspect, builds a proxy, and puts the proxy in the container in place of the original. You never touch the proxy-building code.
Underneath, that post-processor uses a class called ProxyFactory. You can use it directly, without any container. This helps in three situations:
- Unit tests where you want to check how advice behaves without starting a Spring context.
- Objects that are created with
newand are not Spring beans, but still need advice. - Learning. Seeing the factory work shows exactly what the auto-proxy machinery does.
ProxyFactory lives in org.springframework.aop.framework. It extends ProxyCreatorSupport, which extends AdvisedSupport. AdvisedSupport is the class that holds the configuration: the target object, the list of advisors, and the interfaces to implement.
The first proxy
The example below needs the spring-aop library (and spring-core, which it pulls in). The GreetingService and GreetingServiceImpl types are the same ones used in the JDK proxy example earlier in this tutorial.
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactory;
interface GreetingService {
String greet(String name);
}
class GreetingServiceImpl implements GreetingService {
public String greet(String name) {
return "Hello, " + name;
}
}
public class ProxyFactoryDemo {
public static void main(String[] args) {
ProxyFactory factory = new ProxyFactory(new GreetingServiceImpl());
factory.addAdvice((MethodInterceptor) invocation -> {
System.out.println("calling " + invocation.getMethod().getName());
return invocation.proceed();
});
GreetingService proxy = (GreetingService) factory.getProxy();
System.out.println(proxy.greet("Grace"));
}
}The output is:
calling greet
Hello, GraceThree things happen here:
new ProxyFactory(target)stores the target and discovers every interface the target class implements.addAdviceregisters aMethodInterceptor. This is the AOP Alliance interface that Spring uses for around-style advice. Callinginvocation.proceed()is the same idea aspjp.proceed()in an@Aroundaspect.getProxy()builds the proxy object.
Because the target implements GreetingService, the result is a JDK dynamic proxy. You must cast it to the interface, not to GreetingServiceImpl.
How the factory picks the proxy type
ProxyFactory follows the same rules as the auto-proxy creator:
| Situation | Proxy type |
|---|---|
| Target implements at least one interface, and `proxyTargetClass` is false | JDK dynamic proxy |
| Target implements no interfaces | CGLIB subclass proxy |
| `setProxyTargetClass(true)` | CGLIB subclass proxy |
Here is the CGLIB case. The class has no interface, so the factory subclasses it.
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactory;
class Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class CglibFactoryDemo {
public static void main(String[] args) {
ProxyFactory factory = new ProxyFactory(new Calculator());
factory.addAdvice((MethodInterceptor) invocation -> {
Object result = invocation.proceed();
System.out.println(invocation.getMethod().getName() + " returned " + result);
return result;
});
Calculator proxy = (Calculator) factory.getProxy();
proxy.add(2, 3);
System.out.println(proxy.getClass().getSuperclass().getSimpleName());
}
}The last line prints Calculator, because the generated proxy class extends Calculator. The usual CGLIB limits apply: a final class cannot be subclassed, and final or private methods are not intercepted.
Advisors: advice plus a pointcut
addAdvice wraps your advice in an advisor that matches every method. To limit which methods are advised, build the advisor yourself. An advisor is a pair of one pointcut and one piece of advice.
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.NameMatchMethodPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
interface Mailer {
void send(String to);
void close();
}
class SmtpMailer implements Mailer {
public void send(String to) {
System.out.println("sending to " + to);
}
public void close() {
System.out.println("closed");
}
}
public class AdvisorDemo {
public static void main(String[] args) {
NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut();
pointcut.addMethodName("send");
MethodInterceptor logging = invocation -> {
System.out.println("-> " + invocation.getMethod().getName());
return invocation.proceed();
};
Advisor advisor = new DefaultPointcutAdvisor(pointcut, logging);
ProxyFactory factory = new ProxyFactory(new SmtpMailer());
factory.addAdvisor(advisor);
Mailer proxy = (Mailer) factory.getProxy();
proxy.send("[email protected]");
proxy.close();
}
}Only send prints the arrow line. close still reaches the target, but no advice runs for it. This is the same split that an annotation-style aspect makes between pointcut and advice, written out as objects.
If you add several advisors, they run in the order you added them. The first one added is the outermost.
Inspecting the result
A proxy created by the factory implements the Advised interface, so you can query it at runtime:
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
// continuing from the AdvisorDemo above
System.out.println(AopUtils.isAopProxy(proxy));
System.out.println(AopUtils.isJdkDynamicProxy(proxy));
System.out.println(((Advised) proxy).getTargetSource().getTarget().getClass().getSimpleName());
System.out.println(((Advised) proxy).getAdvisors().length);For the mailer this prints true, true, SmtpMailer and 1. These helpers are also the quickest way to debug a Spring bean. If AopUtils.isAopProxy(bean) returns false, no advice can be running.
getTargetSource().getTarget() can throw a checked Exception, so wrap the call in a method that declares throws Exception.
Settings worth knowing
setProxyTargetClass(true)forces CGLIB even when interfaces exist. Use it when callers need to inject the concrete class.setInterfaces(...)limits the proxy to the interfaces you name.setExposeProxy(true)makes the proxy available throughAopContext.currentProxy(). Code inside the target can then call through the proxy, which is one way to escape the self-invocation problem. It ties the target to Spring, so prefer moving the method to another bean.setFrozen(true)stops further changes to the advisor chain, which lets Spring skip some checks and run faster.
Common mistakes
- Casting the proxy to the implementation class when the proxy is a JDK proxy. This throws
ClassCastException. Cast to the interface or force CGLIB. - Keeping a reference to the target and calling it directly. That call bypasses every advisor, exactly like self-invocation.
- Expecting
@Aspectannotations to work with a bareProxyFactory. They do not. For that you useAspectJProxyFactory, which reads@Aspectclasses.
Putting it together
Exercise
A teammate writes ProxyFactory factory = new ProxyFactory(new SmtpMailer());, adds an interceptor, then runs SmtpMailer m = (SmtpMailer) factory.getProxy();. It throws ClassCastException. Why, and what are two ways to fix it?
Show answer
SmtpMailer implements the Mailer interface and proxyTargetClass is false, so the factory builds a JDK dynamic proxy. That proxy implements Mailer but is not a subclass of SmtpMailer. Fix it by casting to Mailer, or by calling factory.setProxyTargetClass(true) before getProxy() so a CGLIB subclass is created.
Exercise
You build a proxy with NameMatchMethodPointcut matching only send, then call proxy.close(). Does the interceptor run, and does close() still execute on the target?
Show answer
The interceptor does not run, because the pointcut does not match close. The call still reaches the target, and close() executes normally.