可运行的 jar 如何在运行时加载外部 xml 文件?

How can a runnable jar load external xml file at runtime?

(这似乎是一个微不足道的问题,但卡住了 2 天:( )

我有一个可运行的 jar(使用 maven assembly plugin 创建)。 jar 中的 class 在 class 路径上查找 xml 文件。但是,我们不想将 xml 文件捆绑在 jar 中,而是希望将其外部化。

尝试到现在:

  1. 在运行时设置class路径:

    java -classpath ./conf -jar my-jar-with-dependencies.jar
    

==> 未加载(conf 文件夹包含 xml)

  1. 在汇编插件中设置class路径

            <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>com.xxx.Test</mainClass>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>./conf/</classpathPrefix>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </plugin>
    

==> 不会在可运行的 jar

中将 ClassPath 添加到 MANIFEST.MF

编辑:

在 jar 中生成 MAINFEST.MF

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: xxx
Build-Jdk: 1.7.0_21
Main-Class: com.xxx.Test

编辑 2:

所以我编辑了 jar 中生成的 MANIFEST 并重新创建了 jar。仍然没有找到 xml!

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: xxx
Build-Jdk: 1.7.0_21
Main-Class: com.xxx.Test
Class-Path: . /* Tried with both . and ./conf */

当您使用 -jar 参数时,您指定的类路径将被忽略。指定为 here

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

JVM 使用清单中指定的类路径。确保清单包含类路径定义。

这个问题似乎没有很好的答案。总结:

  • java -jar 忽略 -cp 选项
  • ClassPath 添加到 manifset 也没有任何效果(不确定这是否是由于库加载 xml 的任何特定方式)

因此,剩下唯一可行的选项是手动调用 class 文件:

$ java -cp <...> MyPackage.MyClass

其中,cp 包含 jar 文件和 conf 文件夹路径。