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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42863382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:28:58  来源:igfitidea点击:

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

javaspringfileintellij-14

提问by Rob_kael

I am trying to set the configuration location for my Project but I keep getting the following error:

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

java.io.FileNotFoundException: class path resource [main/resources/app-context.xml] cannot be opened because it does not exist

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

I have my project set up like this:

我的项目设置如下:

enter image description here

在此处输入图片说明

And I have my code set up as:

我的代码设置为:

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

How can I fix this?

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

采纳答案by JB Nizet

What you put directly under src/main/javais in the default package, at the root of the classpath. It's the same for resources put under src/main/resources: they end up at the root of the classpath.

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

So the path of the resource is app-context.xml, not main/resources/app-context.xml.

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

回答by Mouad EL Fakir

Try this:

尝试这个:

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

回答by Gomsy

The file location/path has to relative to your classpath locations. If resources directory is in your classpath you just need "app-context.xml" as file location.

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

回答by Saurabh Verma

We can also try this solution

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

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

in this the spring automatically finds the class in the class path itself

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