简体   繁体   中英

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

(This seems like a trivial enough problem, but stuck for 2 days :( )

I have a runnable jar (created with maven assembly plugin ). A class inside the jar looks for an xml file on classpath. However, we do not want to bundle the xml file in the jar and want it to be externalized.

Tried till now:

  1. Set the classpath at runtime:

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

==> doesn't load (conf folder contains the xml)

  1. Set classpath in assembler plugin

      <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> 

==> does not add ClassPath to MANIFEST.MF in the runnable jar

Edit:

Generated MAINFEST.MF in the jar:

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

Edit 2 :

So I edited the generated MANIFEST in the jar and recreated jar. Still doesn't find the 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 */

When you use -jar argument classpath you specify is ignored. It is specified 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 use classpath specified in manifest. Make sure that manifest contains classpath definition.

There doesn't seem to be a good answer to this. In summary:

  • java -jar ignores -cp option
  • Adding ClassPath to manifset has no effect either (not sure if it is due to any particular way of how the library loads the xml)

So, the only remaining option that works is to invoke the class file manually:

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

where, cp contains the jar file and conf folder path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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