简体   繁体   English

为什么spring找不到beans.xml?

[英]Why spring cannot find beans.xml?

I am learning spring and put the Beans.xml into main/resources folder.我正在学习 spring 并将 Beans.xml 放入 main/resources 文件夹。 I am using maven to manage project.我正在使用 maven 来管理项目。

However when running, it cannot find the Beans.xml但是在运行时,它找不到 Beans.xml

 ApplicationContext context = new ClassPathXmlApplicationContext(
                "Beans.xml");

The error is Exception in thread "main"错误是线程“main”中的异常

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [Beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [Beans.xml] cannot be opened because it does not exist.

I am using Intellij, want to know why?我正在使用 Intellij,想知道为什么? I am using spring 4.3.4我正在使用弹簧 4.3.4

new ClassPathXmlApplicationContext("file:src/main/resources/beans.xml");

file:前缀指向文件系统资源,而不是类路径。

Despite the @Hiccup's answer is right, but it is not accurate because if your application is FileSystem dependent (using the "file:" prefix) and you package this app and execute it with java commands there will be thrown the same exception, so you can add this prefix:尽管@Hiccup 的答案是正确的,但它并不准确,因为如果您的应用程序依赖于 FileSystem(使用“file:”前缀)并且您打包此应用程序并使用 java 命令执行它,则会抛出相同的异常,因此您可以添加这个前缀:

ApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:Beans.xml");

But this is correct just if you have configured Maven (or Ant or Ivy) to tell IntelliJ to locate resources from main/resources folder.但是,如果您已配置 Maven(或 Ant 或 Ivy)告诉 IntelliJ 从 main/resources 文件夹中定位资源,这是正确的。

So, if the previous affirmation is not your case, you have to move your Beans.xml to src/main/java.所以,如果前面的肯定不是你的情况,你必须将你的 Beans.xml 移动到 src/main/java。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM