Sub topic 7
How Spring decides which proxy to create
This chapter assumes you know what a JDK dynamic proxy and a CGLIB proxy are, from the two previous chapters. It also assumes you can write a basic @Aspect. Here you will learn when Spring creates a proxy, which kind it picks, and how to change that choice.
Where the decision happens
Spring does not create proxies when it instantiates a bean. It creates them afterwards, in a BeanPostProcessor. When you enable AOP, Spring registers AnnotationAwareAspectJAutoProxyCreator, a subclass of AbstractAutoProxyCreator. It runs after each bean is initialized and does the following:
- It collects every advisor in the container. An advisor is a pointcut plus an advice. Each
@Aspectmethod is turned into one. - It checks which advisors have a pointcut that matches at least one method of the bean's class.
- If none match, it returns the original bean. No proxy exists.
- If some match, it fills a
ProxyFactorywith the target, the advisors and the interfaces. It then asks that factory for a proxy. - The proxy replaces the bean in the container. Other beans receive the proxy when they inject it.
Two consequences follow. A bean that no pointcut matches is never proxied, so it costs nothing at runtime. A bean that is proxied is replaced for every consumer, so the injected object is not an instance of your class in the plain sense.
The factory rule
The type of proxy is chosen in DefaultAopProxyFactory.createAopProxy. Its logic reduces to this:
- If
optimizeis true, orproxyTargetClassis true, or the bean has no usable interfaces, Spring uses CGLIB. The exception is when the target type is itself an interface or is already a JDK proxy class. Then it uses a JDK proxy. - Otherwise Spring uses a JDK proxy.
"Reasonable interface" has a precise meaning. Spring ignores configuration callback interfaces such as InitializingBean, DisposableBean, AutoCloseable and the Aware family. It also ignores internal language interfaces such as Groovy's GroovyObject. A bean that implements only AutoCloseable is therefore treated as having no interfaces and gets a CGLIB proxy.
Defaults differ between Spring and Spring Boot
The proxyTargetClass flag is the setting you control most often.
| Setup | Default for `proxyTargetClass` | Bean with an interface | Bean without interfaces |
|---|---|---|---|
| Plain Spring, `@EnableAspectJAutoProxy` | `false` | JDK proxy | CGLIB |
| Spring Boot (`spring.aop.proxy-target-class`) | `true` | CGLIB | CGLIB |
| `@EnableAspectJAutoProxy(proxyTargetClass = true)` | `true` | CGLIB | CGLIB |
Observing the choice
This program starts two contexts, one per mode. It reports the proxy type of two beans. One bean has an interface and the other does not. You need spring-context and aspectjweaver on the classpath.
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
interface GreetingService {
String greet(String name);
}
class GreetingServiceImpl implements GreetingService {
public String greet(String name) {
return "Hello, " + name;
}
}
class Mailer {
public void send(String to) {
System.out.println("sending to " + to);
}
}
@Aspect
class LogAspect {
@Before("execution(* *.greet(..)) || execution(* *.send(..))")
public void log() {
System.out.println("advice ran");
}
}
@Configuration
class Beans {
@Bean GreetingService greetingService() { return new GreetingServiceImpl(); }
@Bean Mailer mailer() { return new Mailer(); }
@Bean LogAspect logAspect() { return new LogAspect(); }
}
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = false)
@Import(Beans.class)
class InterfaceMode { }
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Import(Beans.class)
class ClassMode { }
public class ProxyChoiceDemo {
public static void main(String[] args) {
report("proxyTargetClass=false", InterfaceMode.class);
report("proxyTargetClass=true", ClassMode.class);
}
static void report(String label, Class<?> config) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(config)) {
System.out.println(label);
for (String name : new String[] { "greetingService", "mailer" }) {
Object bean = ctx.getBean(name);
System.out.println(" " + name
+ " jdk=" + AopUtils.isJdkDynamicProxy(bean)
+ " cglib=" + AopUtils.isCglibProxy(bean));
}
}
}
}The output is:
proxyTargetClass=false
greetingService jdk=true cglib=false
mailer jdk=false cglib=true
proxyTargetClass=true
greetingService jdk=false cglib=true
mailer jdk=false cglib=truemailer is CGLIB in both runs because it has no interface to proxy. Only greetingService changes with the flag.
What each choice means for your code
A JDK proxy implements the interfaces of the target. It is not a subclass of the target class. Three things follow:
- Injecting by the concrete type fails with
BeanNotOfRequiredTypeException. Inject the interface instead. - Only methods declared on the proxied interfaces get advice. A public method that exists only on the implementation class is unreachable through the proxy.
- The target class can be
final, since nothing extends it.
A CGLIB proxy is a generated subclass of the target class. Spring creates it with Objenesis, which skips the constructor. Three things follow:
- The class cannot be
final, andfinalmethods cannot be overridden. Calls to afinalmethod run on the proxy instance itself, where the fields are uninitialized and usuallynull. This is a classic source ofNullPointerException. - Constructor side effects run once, on the real target. They do not run again for the proxy.
- You can inject by class or by interface.
Overriding the choice per bean
@EnableAspectJAutoProxy sets one global mode. It applies to every bean that auto-proxying wraps. Two other places can influence a single proxy:
- A
ProxyFactoryyou configure yourself, as in the programmatic chapter, can callsetProxyTargetClass(true)for one target. - With Spring Boot, set
spring.aop.proxy-target-class=falseto restore interface-based proxies globally. Do this only if you have a reason, such as a library class that cannot be subclassed.
Exercise
A bean implements only AutoCloseable. An aspect matches its methods, and proxyTargetClass is false. Which proxy does Spring create, and why?
Show answer
A CGLIB proxy. AutoCloseable is a configuration callback interface, so Spring does not count it as a reasonable proxy interface. The bean is treated as having no interfaces, and Spring switches to class-based proxying.
Exercise
In plain Spring with the default proxyTargetClass=false, a service bean implements GreetingService. Another bean declares @Autowired GreetingServiceImpl service. What happens at startup, and what are two ways to fix it?
Show answer
Startup fails with BeanNotOfRequiredTypeException (or a no-matching-bean error), because the JDK proxy implements GreetingService but is not a GreetingServiceImpl. Fix it by injecting GreetingService, or by setting proxyTargetClass=true so Spring creates a CGLIB subclass.