Spring项目出现BeanNotOfRequiredTypeException: Bean named ‘xxxImpl‘ is expected to be of type ‘xxx‘

╰半夏微凉° 2022-12-09 04:59 197阅读 0赞

运行spring项目时出现Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'xxxImpl' is expected to be of type 'xyz.newtouch.service.impl.XxxImpl' but was actually of type 'com.sun.proxy.$Proxy666(非真实数值)',原因是自动注入时未正确编写注入时的变量修饰对象,例:需要从ioc中注入A接口的实例时未使用A接口来接收注入的内容,而使用了A接口的实现类来接收,伪代码如下:

  1. public interface A {
  2. }
  3. @Component
  4. class B implements A {
  5. }
  6. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  7. @RunWith(SpringJUnit4ClassRunner.class)
  8. class XxxTest {
  9. @Autowired
  10. private B b;
  11. @Test
  12. public void test1() {
  13. System.err.println(b);
  14. }
  15. }

此时应该使用A来修饰被注入的对象,因为存在接口时spring默认使用JDK动态代理,如果不存在接口才默认使用cglib动态代理(也可以直接指定全部使用cglib动态代理),cglib动态代理的情况下才可以直接使用实现类进行注入

发表评论

表情:
评论列表 (有 0 条评论,197人围观)

还没有评论,来说两句吧...

相关阅读