Spring容器生成Bean 的时候使用后置处理起对Bean进行增强(AOP)
实际时通过动态代理生成代理对象
没有实现接口的Bean会使用CGLIB生成代理对象,而生成的这个代理对象实现了多个接口
0 = {Class@6811} “interface org.springframework.aop.SpringProxy”
1 = {Class@6800} “interface org.springframework.aop.framework.Advised”
2 = {Class@8990} “interface org.springframework.cglib.proxy.Factory”
因此在存在多个后置处理器,并且后置处理起会对对象进行代理的情况下不使用proxy-target-class指定使用CGLIB代理的话会使用jdk代理
最终生成的代理对象是一个实现了上述接口的代理类对象,真实类型被清除了
导致最终生成完Bean注入到其他类种的时候会产生如下错误信息
BeanNotOfRequiredTypeException: Bean named ‘XXX’ is expected to be of type ‘XXX’ but was actually of type ‘com.sun.proxy.$ProxyXXX’
The bean ‘xxx’ could not be injected as a ‘xxx’ because it is a JDK dynamic proxy that implements:
结论:
虽然spring会通过原始对象自动切换jdk代理或cglib代理但是如果存在需要嵌套进行代理增强的场景可能会出错.
springboot2.0.x版本默认使用cglib