Spring项目中ClassPathXmlApplicationContext加载XML文件报错求助
Maven项目Spring配置文件加载路径问题解决
问题描述
使用Eclipse创建Maven项目,通过以下代码加载Spring XML配置文件:
ApplicationContext context=new ClassPathXmlApplicationContext("com/springcore.collections/collectionconfig.xml");
出现加载失败错误,报错信息:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [com/springcore.collections/collectionconfig.xml]
项目目录结构:src/main/java下存在com/springcore/collections包,配置文件当前放置在该包目录下或其他非类路径资源目录。
解决方案
- 调整配置文件存放位置:Maven项目的类路径资源默认读取
src/main/resources目录。需在该目录下创建对应包结构com/springcore/collections,将collectionconfig.xml移入此目录。 - 确认路径写法:配置文件在
src/main/resources/com/springcore/collections/下时,原代码中的路径写法com/springcore/collections/collectionconfig.xml是正确的;若直接放在src/main/resources根目录,路径改为collectionconfig.xml即可。 - 检查Maven资源配置:确保pom.xml未排除资源文件,默认配置会将
src/main/resources下的文件复制到类路径。若自定义了<resources>节点,需保证包含该目录的文件。 - 清理重构项目:在Eclipse中右键项目 → Maven → Clean,再执行Maven → Install,确保资源文件被正确编译到
target/classes目录(类路径核心目录)。
内容的提问来源于stack exchange,提问作者pratiksha
相关产品推荐
相关产品推荐

