org.springframework.beans.factory.BeanNotOfRequiredTypeException错误
错误信息:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.dbzhang.demo3.Demo3': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userDao' must be of type [com.dbzhang.demo3.UserDaoImpl], but was actually of type [com.sun.proxy.$Proxy12]
错误代码:
package com.dbzhang.demo3; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext3.xml") public class Demo3 { @Resource(name="userDao") private UserDaoImpl userDao; @Test public void run(){ userDao.save(); } }
出现这种情况的原因:当使用annotation方式注入spring的bean的时候出现的,这里的spring代理机制采用的是JDK动态代理机制,
其中JDK动态代理机制,只能实现对接口的注入,不能实现类的注入,而UserDaoImpl是一个实现类,不能采用JDK动态代理机制;因此需要改正:
package com.dbzhang.demo3; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext3.xml") public class Demo3 { @Resource(name="userDao") private UserDao userDao; @Test public void run(){ userDao.save(); } }
可以参看如下文章:https://blog.csdn.net/jyp360/article/details/70215002
请使用手机"扫一扫"x