java.io.FileNotFoundException:无法打开类路径资源,因为它不存在

Rob*_*ael 12 java spring file intellij-14

我正在尝试为我的项目设置配置位置,但我不断收到以下错误:

java.io.FileNotFoundException:无法打开类路径资源[main/resources/app-context.xml],因为它不存在

我的项目设置如下:

在此输入图像描述

我将我的代码设置为:

ApplicationContext context = new ClassPathXmlApplicationContext(configLocation: "main/resources/app-context.xml");
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

JB *_*zet 19

您直接置于src/main/java下的是默认包,位于类路径的根目录下.对于放在src/main/resources下的资源也是如此:它们最终位于类路径的根部.

所以资源的路径是app-context.xml,而不是main/resources/app-context.xml.


Sau*_*rma 6

我们也可以试试这个解决方案

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml");
Run Code Online (Sandbox Code Playgroud)

在这种情况下,spring 会自动在类路径本身中找到该类

  • 它似乎也适用于带有 `@ImportResource("classpath*:config.xml")` 的 Spring Boot (3认同)