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

如何解决Spring中class path resource [config.xml]不存在引发的FileNotFoundException

Spring配置文件config.xml找不到的解决办法

问题详情

运行Spring代码时触发以下异常:

  • Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [config.xml]
  • Caused by: java.io.FileNotFoundException: class path resource [config.xml] cannot be opened because it does not exist

主代码实现:

package org.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext context = new GenericXmlApplicationContext("config.xml");
        Student s1= (Student) context.getBean("student1");
        System.out.println(s1);
    }
}

已尝试将config.xml放置在项目根目录(src目录外),但问题未解决。

解决方案

1. 放置配置文件到正确的类路径目录

GenericXmlApplicationContext默认从**类路径(classpath)**加载配置文件,需将config.xml放在对应位置:

  • Maven/Gradle项目:放在src/main/resources目录(这是Maven默认的资源目录,会被自动加入类路径)
  • 普通Java项目:放在src目录下,并确保IDE将src标记为「Source Root」

2. 确认资源目录的IDE配置

确保存放配置文件的目录被IDE识别为资源目录:

  • IntelliJ IDEA:右键目标目录 → Mark Directory as → Resources Root
  • Eclipse:右键目标目录 → Build Path → Use as Source Folder

3. 明确指定类路径路径

如果配置文件在子目录中,或需要明确指定类路径,可修改代码:

// 明确使用classpath前缀
ApplicationContext context = new GenericXmlApplicationContext("classpath:config.xml");

// 若文件在子目录,比如resources/config/下
ApplicationContext context = new GenericXmlApplicationContext("classpath:config/config.xml");

4. 验证编译输出

确认编译后config.xml已被复制到编译输出目录:

  • Maven项目:执行mvn clean compile后,检查target/classes目录下是否存在config.xml
  • 普通项目:查看IDE的编译输出目录(如bin),确认资源文件已被复制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:28:15