【异常篇-spring】org.springframework.beans.factory.BeanNotOfRequiredTypeException

本文解析了一个关于Spring框架中依赖注入出现类型不匹配的问题,并提供了解决方案。问题出现在使用@Resource注解时未明确指定bean名称,导致Spring选择了错误的服务实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错异常:

2018-03-01 13:44:18.091 [localhost-startStop-1] ERROR o.a.c.c.C.[.[.[/zsedu-score-query-webserver-webapp] -- StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scoreQueryController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'studentService' must be of type [com.nenglong.rrt.webserver.service.exam.StudentService], but was actually of type [com.nenglong.rrt.webserver.service.user.impl.StudentServiceImpl$$EnhancerBySpringCGLIB$$9f0ce91f]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(Common...............................
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'studentService' must be of type [com.xxx.webserver.service.exam.StudentService], but was actually of type [com.xxx.webserver.service.user.impl.StudentServiceImpl$$EnhancerBySpringCGLIB$$9f0ce91f]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:364)

..............................

解决方法:

@Resource
private StudentService<Student, StudentForm> studentService;

改为

@Resource(name="studentService2")
	private StudentService<Student, StudentForm> studentService;

原理:默认按照名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找。com.xxx.webserver.service.user包下也有一个studentService接口,取bean时未指定名称导致到的..service.user包下的接口类型不匹配。

备注:...user包下的studentService实现类代码

@Service("studentService")
public class StudentServiceImpl implements studentService 
{
	.......
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值