AOP and proxies · Topic 4 of 5
JDK and CGLIB proxies
Definition​
Spring adds behaviour by wrapping a bean in a proxy. If the bean implements an interface Spring can use a JDK proxy, which implements the same interface. Otherwise (or when forced) it subclasses the class with CGLIB. Spring Boot uses CGLIB by default.
Example code​
Which kind of proxy you get
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;
interface Greeter { String greet(); }
class PoliteGreeter implements Greeter {
public String greet() { return "Good morning"; }
}
class PlainService {
public String run() { return "done"; }
}
class Demo {
public static void main(String[] args) {
ProxyFactory withInterface = new ProxyFactory(new PoliteGreeter()); // has an interface
Object jdkProxy = withInterface.getProxy();
System.out.println("JDK proxy: " + AopUtils.isJdkDynamicProxy(jdkProxy));
ProxyFactory withoutInterface = new ProxyFactory(new PlainService()); // a class with no interface
Object cglibProxy = withoutInterface.getProxy();
System.out.println("CGLIB proxy: " + AopUtils.isCglibProxy(cglibProxy));
System.out.println(((Greeter) jdkProxy).greet());
}
}
// Output:
// JDK proxy: true
// CGLIB proxy: true
// Good morning
Finished this page? Track your progress (saved only in your browser).