如何 运行 IntelliJ 中需要文件位于 class 路径中的 Maven 项目?

How to run maven project in IntelliJ that requires a file to be in class path?

我正在研究这个 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 到构建工件的类路径的文件。 java 包含未复制到构建工件的文件(.java 文件未复制到工件,因此您的 XML 文件也不会)

尝试将 ch2-beans.xmlmain 移动到 resources,同时保留其余路径。

在您刚要放在开头的文件中:

@ComponentScan("com.wiley.beginningspring")
@PropertySources(value = {@PropertySource("classpath:ch2-beans.xml")})

它会搜索 class 路径中的任何地方。

使用 class 变量:

@Resource
private Environment env;

获取文件内容如:

String yourPropertyValue = env.getRequiredProperty("your_property_name");

这是答案:

因此,当您编译 Java 代码时,会创建 .class 文件。 classJVM 将使用的 .class 文件所在的路径和 运行 您的代码所在的路径。我告诉你去模块设置->模块-->路径的原因是在那里你可以看到你的 .class 文件所在的编译输出路径。 JVM 很容易找到您的 .xml 文件并从中获取信息。

回答你的第二个问题,如何在没有 IDE 的情况下使用它。如果你只有一个 Java 文件,它很简单:

打开你的 Mac OS X 终端。将目录更改为您拥有 java 文件的项目。现在给出命令:

javac filename.java

现在 javac 表示编译器将编译您的文件。并创建一个名为文件名的二进制文件。你可以简单地通过说

来执行它
java filename

注意,我第二次没有给出扩展名,因为它现在是一个二进制文件。如果有多个java个文件,可以使用:

javac filename1.java filenam2.java

我不建议只使用控制台,对于高级的东西你需要 IDE。有任何疑问,让我知道。