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

问题描述 投票:0回答:8

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

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

我的项目是这样设置的:

enter image description here

我的代码设置为:

ApplicationContext context = new ClassPathXmlApplicationContext(configLocation: "main/resources/app-context.xml");

我该如何解决这个问题?

java spring file intellij-14
8个回答
51
投票

直接放在

src/main/java
下的内容位于默认包中,位于类路径的根目录下。对于放在
src/main/resources
下的资源也是如此:它们最终位于类路径的根部。

所以资源的路径是

app-context.xml
,而不是
main/resources/app-context.xml


8
投票

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

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml");

在此,spring 自动在类路径本身中查找类


2
投票

试试这个:

ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

1
投票

文件位置/路径必须相对于您的类路径位置。如果资源目录位于您的类路径中,您只需要“app-context.xml”作为文件位置。


0
投票

这对我有用

ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");


0
投票

对于 Eclipse - 跟随路径

Build path -> Configure build path -> go to sources -> add folder
标记包含 XML 文件的资源文件夹。 现在,如果您尝试运行它就会运行得很好。


0
投票

您可以使用下面的内容来阅读资源。它将提供输入流。

InputStream in = MyClass.class.getClassLoader().getResourceAsStream("files.properties");

0
投票

对于我的情况,我正在运行一些测试并面临这些错误:

java.lang.IllegalStateException: Unable to load JSON from class path resource [com/springproject/cashcard/expected.json]
and
java.io.FileNotFoundException: class path resource [com/springproject/cashcard/expected.json] cannot be opened because it does not exist

所以,我注意到

test/resources
模块丢失了。因此,我将其添加到类路径中,添加了 JSON 文件并重建了项目,结果成功了。

© www.soinside.com 2019 - 2024. All rights reserved.