Wednesday, April 27, 2016

Dynamic Proxy: JDK VS CGLIB

If target object implements interface, by default, spring will use Dynamic Proxy from JDK for AOP.
If target object implements interface, we can force to use CGLIB to make Dynamic Proxy for AOP.
If target object does not implements interface, we MUST use CGLIB to make Dynamic Proxy for AOP.

In conclusion:
JDK can only apply to class which implements interface
CGLIB can apply to class with/without implementing interface

Spring will dynamically choose to use JDK or CGLIB for each target object.


JDK proxy example:
userManager $Proxy2  (id=42)
h JdkDynamicAopProxy  (id=54)

CGLIB example:
UserManagerImpl$$EnhancerBySpringCGLIB$$7f895f28  (id=46)

You can see CGLIB extends the target class to generate proxy, JDK did not
Because CGLIB do extends, our target class should NOT be final

to Enable CGLIB:

dependency:
<dependency>
 <groupId>cglib</groupId>
 <artifactId>cglib</artifactId>
 <version>3.2.2</version>
</dependency>

applicationContext.xml config

<!-- proxy-target-class="true" means force to use CGLIB -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

But if we want spring to choose for us, we don't have to force to do the config, just add dependency.






No comments:

Post a Comment