简体   繁体   English

将外部属性文件添加到类路径

[英]Add external properties file to classpath

My application is packaged into a jar file and is run with the regular "java -jar ..." command. 我的应用程序打包到jar文件中,并使用常规的“ java -jar ...”命令运行。

I have a properties file "myApp.properties" in the directory: /opt/myuser/resources 我在以下目录中有一个属性文件“ myApp.properties”:/ opt / myuser / resources

I want to add the /opt/myuser/resources directory to the classpath. 我想将/ opt / myuser / resources目录添加到类路径。 I believe this is advantageous because when the properties files are on the classpath, I can access the properties files in my source code without specifying the full path to the properties files (/opt/myuser/resources/myApp.properties). 我认为这是有好处的,因为当属性文件位于类路径上时,无需指定属性文件的完整路径(/opt/myuser/resources/myApp.properties),就可以访问源代码中的属性文件。 This way I can keep a properties file with environment-specific properties separate from my application. 这样,我可以将具有特定于环境的属性的属性文件与应用程序分开。

I've tried to set the classpath using instructions from Oracle ( http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/classpath.html under "Using the JDK tools' -classpath option") like this: 我尝试使用来自Oracle的说明来设置类路径( http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/classpath.html,在“使用JDK工具的-classpath选项”下)像这样:

java -cp .:/opt/myuser/resources -jar myApp.jar

but I get an error that the properties file myApp.properties (referenced in the source code) cannot be opened: 但出现错误,无法打开属性文件myApp.properties(在源代码中引用):

Caused by: java.io.FileNotFoundException: class path resource [myApp.properties] cannot be opened because it does not exist

Am I going about this the wrong way? 我会以错误的方式处理吗? Should I edit the classpath in another way? 我应该以其他方式编辑类路径吗?

Hopefully this will help someone else. 希望这会帮助其他人。 I've used as program arguments for spring boot --spring.config.location=file:/opt/myuser/resources/myApp.properties 我已经用作spring boot --spring.config.location = file:/opt/myuser/resources/myApp.properties的程序参数

and then it will use that file. 然后它将使用该文件。

use gerResource solutions to load file on your Properties Object: 使用gerResource解决方案在Properties对象上加载文件:

  ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
  Class.getResourceAsStream ("/some/pkg/resource.properties");
  ResourceBundle.getBundle ("some.pkg.resource");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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