Java -jar:访问外部配置文件

Joe*_*oel 9 java configuration jar external classpath

我正在寻找一些我认为不会有困难的事情.

我有一个应用程序,我想打包成jar,因为我有~30个依赖项,我希望能够部署单个文件.

我有一些配置文件 - 属性文件和弹簧配置文件,以及我的log4道具文件 - 我希望在jar外部.我想我希望如果我将它们放在与jar相同的目录中,它会在运行时找到它们,但事实并非如此.

在开发过程中,我将这些文件放在我的eclipse项目的类路径的根目录下,应用程序发现它们就好了.我觉得我错过了jar/classpath理论的一些关键方面......

所以我想要的是能够将配置文件和jar放在同一目录中,并让我的应用程序找到配置文件,当我用标准的java -jar运行它时.

有没有一种简单的方法来实现这一目标?

Joe*_*oel 11

我会为后人保留我对这个问题的解决方案.

我认为我可能期望java -jar做一些它不做的事情.

如果你使用常规的java命令,你可以在类路径中包含jar,你最终会得到与java -jar几乎相同的东西,只需要专门命名你想要使用的类.它看起来像这样:

java -cp .:path/to/Jar.jar com.company.package.Class arg1=val1 arg2=val2 ....
Run Code Online (Sandbox Code Playgroud)

你有可能会为你创建一个脚本来启动程序,所以命令行调用的额外复杂性实际上并不多,因为你只会构建它一次.

你会看到我包括'.' 作为类路径中的第一项,这意味着与jar相同的目录中的任何内容也将包含在类路径中.当然jar中的所有内容也包含在类路径中,因为jar本身也在类路径中.

您还会看到我已经展示了如何在命令行中输入args.这是我不确定什么时候我开始但它按预期工作.

我确信这只是基本的Java部署知识,但由于某种原因我缺乏它.

我希望这有助于其他人.如果有人能说"不要试图让-jar工作 - 只需使用-cp方法",那肯定会节省我很多时间......


Jay*_* R. 5

您需要添加“。” 到要为应用程序构建的jar文件的类路径。

所以在清单中,我希望看到

Main-Class: some.full.Name
Class-Path: . needed-lib.jar other-lib.jar 
Run Code Online (Sandbox Code Playgroud)

然后,当您通过执行

java -jar myapp.jar
Run Code Online (Sandbox Code Playgroud)

它实际上使用

java -classpath .;needed-lib.jar;other-lib.jar some.full.Name
Run Code Online (Sandbox Code Playgroud)

这样,带有myapp.jar文件的目录中的任何文件也将位于类路径上。该类路径是相对于包含它的jar的位置的。

Log4j for one expects the log4j.xml configuration file to be on the classpath. If you aren't using the name log4j.xml you also have to add a system property to your start up command to tell the log4j library to look for a different name.

I'm not sure what Spring expects for configuration files. And property file loading depends on what mechanism is used to load the file. Using a FileReader or InputStream doesn't use the classpath mechanism at all. In that case you need to know where the application is expecting the file to be relative to the current working directory.