spring 动态代理Bean named 'userService' is expected to be of type 'cn.msg.service.impl.UserServiceImpl'

这个异常错了一下午。。。。。

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 
'userService' is expected to be of type 'cn.msg.service.impl.UserServiceImpl' 
but was actually of type 'com.sun.proxy.$Proxy7'

最后终于在我的知识盲区中找到了解决方案,然后又了解了一下
这个问题出现的原因:一般在使用annotation的方式注入spring的bean 出现的,具体是由于spring采用代理的机制导致的,看使用的代码:
在这里插入图片描述
看代码也没什么问题但是关于动态代理就有问题了:
默认动态代理是jdk动态代理,而jdk动态代理不支持类注入也就是依赖注入的对象不能是类,只能是接口
解决方法:proxy-target-class
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。首先说明下proxy-target-class="true"和proxy-target-class="false"的区别,为true则是基于类的代理将起作用(需要cglib库),为false或者省略这个属性,则标准的JDK 基于接口的代理将起作用。
所以遇到这种问题可以在以下标签中根据需求设置代理:

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<aop:config proxy-target-class="true">
<cache:annotation-driven proxy-target-class="true"/>
发布了45 篇原创文章 · 获赞 47 · 访问量 1686

猜你喜欢

转载自blog.csdn.net/qq_44784185/article/details/104363478