JDK动态代理和CGLIB代理的比较

1.如果需要代理的目标类没有实现任何接口,则ProxyFactoryBean会创建基于CGLIB的代理。这种情况是最容易的场景。因为jdk动态代理是基于接口的,因此没有实现接口就意味着jdk动态代理是不可能的。

2.如果需要代理的目标类实现了一个或多个接口,则被创建的代理的类型跟ProxyFactoryBean的配置有关。如果ProxyFactoryBean的属性proxyTargetClass被设置成true,则基于CGLIB的代理会被创建,即使ProxyFactoryBean的属性被设置成一个或多个合格的接口全类名,proxyTargetClass属性设置为true的事实将导致基于CGLIB的代理将生效。

3.CGLIB工作原理:CGLIB代理通过在运行时生成目标类的子类来工作,spring配置这个生成的子类,将方法调用委托给原始目标类:子类实现装饰模式,在advice中织入。CGLIB代理通常应该对用户透明。 但是,有一些问题需要考虑:

• Final methods can’t be advised, as they can’t be overridden.
• There is no need to add CGLIB to your classpath. As of Spring 3.2, CGLIB is repackaged and included
in the spring-core JAR. In other words, CGLIB-based AOP will work "out of the box" just as do JDK
dynamic proxies.

猜你喜欢

转载自blog.csdn.net/leftmumu/article/details/80223087