Spring报错:BeanNotOfRequiredTypeException but was actually of type "com.sun.proxy.$Proxy" 开启cglib代理

报错

项目集成redis,在加上@Cacheable报错,加redis做缓存后项目报错

Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'UserService' is expected to be of type 'com.cmx.demo.UserService' but was actually of type 'com.sun.proxy.$Proxy84'
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1510)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1489)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
	at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:518)
	at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496)
	at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:627)
	at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
	at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
	... 57 more

原因

Bean named 'UserService' is expected to be of type 'com.cmx.demo.UserService' but was actually of type 'com.sun.proxy.$Proxy84'

从报错可以看出 ‘com.sun.proxy.$Proxy84’ 不是我们期待的bean ‘UserService’

原因是我们加了@Cacheable注解,该注解将会在方法前进行拦截,验证当前参数是否存在缓存,如果不存在在进行方法执行,最后在返回后进行将key value缓存。这个拦截使用到了AOP的思想,面向切面编程,有JDK代理和Cglib代理2种,但是底层默认是JDK代理。但是JDK代理有个致命的缺点,就是只能代理有实现过接口的类,而Cglib则都可以代理

当前项目起不来的原因正是我们的UserService没有实现接口,正常情况下应该是UserService实现IUserService

解决方案

  1. 将每个Service或者需要使用到代理的类都实现接口,但是被增强的也只能是接口中的方法
  2. 强制使用Cglib代理
    在spring.xml中开启强制cglib代理,并且新增2个jar包(aspectjrt、aspectjweaver)
<aop:aspectj-autoproxy proxy-target-class="true"/>

cglib代理

发布了37 篇原创文章 · 获赞 21 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/chaitoudaren/article/details/105089235