spring boot 项目运行报错:
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'xxService' is expected to be of type 'com.yangxd.application.service.xxService' but was actually of type 'com.sun.proxy.$Proxy48'
解决办法:启动类增加 @EnableAspectJAutoProxy(proxyTargetClass = true)
注解即可。
阅读以下源码很容易看出,如果目标类是接口或者代理类,使用 jdk 动态代理,否则使用 cglib 代理。
在 spring boot 启动类中添加 @EnableAspectJAutoProxy(proxyTargetClass = true)
,会激活 CglibAutoProxyConfiguration,启用 cglib 代理。
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
Class<?>[] ifcs = config.getProxiedInterfaces();
return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
}
}