众所周知,springboot开启AOP需要在启动类加上注解 @EnableAspectJAutoProxy ,但开发过程中发现即使不加@EnableAspectJAutoProxy 注解,bean还是被代理过,而且是Cglib代理对象。
此时在启动类加上@EnableAspectJAutoProxy(proxyTargetClass = false)关闭cglib代理,但发现 proxyTargetClass 参数设置无效,生成的代理bean仍为cglib代理。
跟踪源码发现在处理aop过程中,aop入口类 @EnableAspectJAutoProxy -> spectJAutoProxyRegistrar -> registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source) 发现连续进入了两次注册方法,其中一次指定的 proxyTargetClass为true,跟踪 ConfigurationClassPostProcessor中处理Import类的方法,发现另一个标注了 @EnableAspectJAutoProxy 注解的类:AopAutoConfiguration,这个类是springboot的自动配置类,也就是说springboot默认自动开启了AOP,
@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class, AnnotatedElement.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = false)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",
matchIfMissing = false)
public static class JdkDynamicAutoProxyConfiguration {
}
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
matchIfMissing = true)
public static class CglibAutoProxyConfiguration {
}
}
其中参数proxy-target-class ,从配置spring.aop.auto读取,默认为true
因此在配置文件中加上spring.aop.auto=false后,代理对象变成了JdkDynamic
我的springboot版本为2.1.x,可以看到默认已经采用cglib代理,个人也感觉不到什么不一样,性能上讲,其实jdk1.8后JdkDynamic性能并不差,不过使用 cglib 后可以直接用实现类注入
比如
@Autowired
ServiceImpl service
毕竟在开发过程中我们的bean中的方法并不一定都在接口中定义,可能会从其他类中继承,这样用接口注入就无法访问这些方法,只能接使用实现类注入,采用cglib可满足这一需求