我正在研究这个book我在运行示例代码时遇到困难。
我导致问题的代码是:
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/com/wiley/beginningspring/ch2/ch2-beans.xml");
我收到的错误是:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [com/wiley/beginningspring/ch2/ch2-beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [com/wiley/beginningspring/ch2/ch2-beans.xml] cannot be opened because it does not exist
我尝试的是,在 IntelliJ 中,将代码导入为 Maven 项目并进行全新安装:
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xml-based-configuration ---
[INFO] Installing /Users/koraytugay/Downloads/spring-book-ch2/xml-based-configuration/target/xml-based-configuration-0.0.1-SNAPSHOT.jar to /Users/koraytugay/.m2/repository/com/wiley/beginningspring/xml-based-configuration/0.0.1-SNAPSHOT/xml-based-configuration-0.0.1-SNAPSHOT.jar
[INFO] Installing /Users/koraytugay/Downloads/spring-book-ch2/xml-based-configuration/pom.xml to /Users/koraytugay/.m2/repository/com/wiley/beginningspring/xml-based-configuration/0.0.1-SNAPSHOT/xml-based-configuration-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
然后我右键单击 Main.java 中的 main 方法并单击运行,但收到错误
"/com/wiley/beginningspring/ch2/ch2-beans.xml"
在类路径中找不到 。解决这个问题的正确方法是什么?
我的运行配置如下:
编辑 01: 我可以使示例像这样工作,但我想了解类路径解决方案:
FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext("/Users/koraytugay/Downloads/spring-book-ch2/xml-based-configuration/src/main/java/com/wiley/beginningspring/ch2/ch2-beans.xml");
编辑02: 也有效的解决方案:
最佳答案
通常资源不会放在 src/main/java
中,而是放在 src/main/resources
中。 resources
包含 Maven will copy 的文件到构建 Artifact 的类路径。 java
包含未复制到构建 Artifact 的文件(.java
文件不会复制到 Artifact ,因此您的 XML 文件也不会复制到 Artifact )
尝试将 ch2-beans.xml
从 main
移动到 resources
,同时保留路径的其余部分。
关于java - 如何在需要文件位于类路径中的IntelliJ中运行maven项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31119000/