Spring Maven项目AppConfig.xml文件FileNotFoundException求助
项目情况
- 项目名称:MavenfirstProject(Maven构建的Spring项目)
- 项目结构:
src ├── main │ ├── java │ │ └── in.sp.main.App.java │ └── resources │ └── AppConfig.xml └── test
问题现象
使用ClassPathXmlApplicationContext加载AppConfig.xml时,持续抛出FileNotFoundException,错误信息如下:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [in/sp/resources/AppConfig.xml]
Caused by: java.io.FileNotFoundException: class path resource [in/sp/resources/AppConfig.xml] cannot be opened because it does not exist
已尝试的操作
- 确认
AppConfig.xml确实放置在src/main/resources目录(该目录默认会被加入类路径) - 使用以下代码加载配置:
String file = "in/sp/resources/AppConfig.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(file);
- 在IntelliJ中清理并重建项目,确认文件已复制到
target/classes目录
问题原因
Maven的src/main/resources是默认资源目录,这里的文件编译后会直接放到target/classes的根路径下,不会保留in/sp/resources这类包结构。当前代码指定了错误的路径,Spring会去类路径下的in/sp/resources/目录查找文件,但实际上AppConfig.xml就在类路径根目录。
解决方法
直接修改加载代码,使用文件名即可:
ApplicationContext context = new ClassPathXmlApplicationContext("AppConfig.xml");
如果需要加载多个配置文件,也可以用数组形式:
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"AppConfig.xml"});
另外可以再检查下target/classes目录里是否存在AppConfig.xml,如果没有,就去IntelliJ里确认资源目录配置是否正确:
- 右键项目 → Open Module Settings → Modules → 选中当前模块 → 切换到Paths标签页,确保
resources目录的输出路径是target/classes - 要是Maven的默认配置被修改过,也可以在
pom.xml里明确配置资源目录:
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
内容的提问来源于stack exchange,提问作者d1vyanshu_Nayak

