Springboot默认使用的是Cglib动态代理
案例一:TransactionAutoConfiguration配置类
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration
@Configuration(proxyBeanMethods = false)@ConditionalOnBean(TransactionManager.class)@ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)public static class EnableTransactionManagementConfiguration {@Configuration(proxyBeanMethods = false)@EnableTransactionManagement(proxyTargetClass = false)@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",matchIfMissing = false)public static class JdkDynamicAutoProxyConfiguration {}@Configuration(proxyBeanMethods = false)@EnableTransactionManagement(proxyTargetClass = true)@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",matchIfMissing = true)public static class CglibAutoProxyConfiguration {}}
案例二:AopAutoConfiguration配置类
@Configuration(proxyBeanMethods = false)@ConditionalOnClass(Advice.class)static class AspectJAutoProxyingConfiguration {@Configuration(proxyBeanMethods = false)@EnableAspectJAutoProxy(proxyTargetClass = false)@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",matchIfMissing = false)static class JdkDynamicAutoProxyConfiguration {}@Configuration(proxyBeanMethods = false)@EnableAspectJAutoProxy(proxyTargetClass = true)@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",matchIfMissing = true)static class CglibAutoProxyConfiguration {}}
JDK动态代理与Cglib动态代理
为什么Springboot会使用Cglib动态代理
- 性能和速度: Cglib 动态代理在性能上通常比标准的JDK 动态代理更快。Cglib 直接通过字节码生成子类来实现代理,避免了一些反射操作,因此在方法调用等方面通常更加高效。
- 无需接口: JDK 动态代理要求目标类必须实现一个接口,而 Cglib 动态代理不需要。这使得 Cglib 更适用于那些没有接口的类,从而扩展了动态代理的适用范围。
- 无侵入性: Spring Boot 选择 Cglib 动态代理可以使你的类无需实现任何接口或继承特定的类,从而减少了对源代码的侵入性。这对于集成第三方库或需要代理的现有类特别有用。
- 方便集成: Spring Boot 默认提供了 Cglib 相关的依赖,因此在应用程序中使用 Cglib 动态代理非常方便。