Difference between JDK dynamic proxy and CGLib proxy in Spring

SpringObject Oriented ProgrammingProgramming

Spring AOP is proxy based. Spring used two types of proxy strategy one is JDK dynamic proxy and other one is CGLIB proxy.

JDK dynamic proxy is available with the JDK. It can be only proxy by interface so target class needs to implement interface. In your is implementing one or more interface then spring will automatically use JDK dynamic proxies.

On the other hand, CGLIB is a third party library which spring used for creating proxy. It can create proxy by subclassing. Spring uses CGLIB for proxy if class is not implementing interface.

Sr. No.KeyJDK dynamic proxyCGLIB proxy
1
Basic
It can be only proxy by interface so target class needs to implement interface
It can create proxy by subclassing
2
Package
It is available with the Java
It is a third  library.
3
Performance
It is a bit slow than CGLIB proxy
It is faster than JDK dynamic proxy
4.
Final
Final class and Final method can not be proxy
Final class and Final method can not be proxy
5..
Use case
Spring uses JDK proxy when is class is implementing one or more interface
Spring uses CGLib proxy when class in not implementing interface
raja
Published on 09-Sep-2020 12:58:05
Advertisements