You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring无法找到同包下spring-context.xml 用classpath*后提示无vehicle bean问题

问题解决方案

1. 无法找到同包下spring-context.xml问题

产生原因:ClassPathXmlApplicationContext默认从类路径根目录检索配置文件,而非当前执行类的包路径。
两种修复方案:

  • 将spring-context.xml移动到项目的src/main/resources根目录(Maven/Gradle项目默认类路径根为该目录),直接使用classpath:spring-context.xml加载
  • 保留xml在源码包的话,加载时写全包路径,比如xml在com.example.demo包下,路径写为classpath:com/example/demo/spring-context.xml

问题截图:
问题截图1

2. 使用classpath*:后提示No bean named "vehicle" has been defined问题

产生原因:classpath*:会匹配加载所有类路径下(包括所有依赖jar包)同名的spring-context.xml,大概率是加载到了其他jar包内的空同名配置,你自己编写的带vehicle bean的配置未被正确加载。
按以下步骤排查修复:

  • 确认配置文件中vehicle bean的id拼写完全正确,Spring bean id大小写敏感
  • 检查项目构建配置,确保xml文件被正确编译到classes目录:Maven项目默认不会扫描java源码目录下的xml文件,需要在pom.xml中添加资源扫描规则:
<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.xml</include>
      </includes>
    </resource>
    <resource>
      <directory>src/main/resources</directory>
    </resource>
  </resources>
</build>
  • 替换classpath*:为classpath:,指定准确的配置文件路径,避免加载多余的同名配置文件

问题截图:
问题截图2

内容的提问来源于stack exchange,提问作者Knightly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:36:04