Spring项目报NoSuchBeanDefinitionException无car bean问题咨询
错误原因
你虽然给Car类添加了@Component注解,但Spring的XML配置文件没有开启组件扫描,Spring不会自动识别代码里的@Component等注解,自然不会把Car类注册为容器中的Bean,调用getBean("car")时就会触发找不到Bean的报错,该问题和web.xml、customerService映射无关。
修正方案
在Spring.xml配置中新增组件扫描配置,指定Spring需要扫描注解的包路径即可:
<context:component-scan base-package="om.venkatesh.omshakthi" />
修改后完整的Spring.xml如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 新增组件扫描配置 --> <context:component-scan base-package="om.venkatesh.omshakthi" /> <bean id="tyre" class="om.venkatesh.omshakthi.Tyre"> </bean> </beans>
Spring默认会把不带自定义名称的@Component类的首字母小写作为Bean名,Car类对应的默认Bean名就是car,和你代码里的获取逻辑匹配,无需额外修改注解。
内容的提问来源于stack exchange,提问作者user17225291
相关产品推荐
相关产品推荐

