我们希望将 .properties 文件保留在 jar 之外,以便我们可以更改模块中使用的属性,而不必重新安装该模块。
在 Java 8 之前,我们曾经通过以下方式运行脚本并包含 .properties 文件,并且它有效。但是自从我们更新到Java 8后,这种在类路径中包含.properties文件的方式就不起作用了,意味着java程序无法找到.properties文件。
我的运行java项目的脚本:
/usr/java/latest/bin/java -d64 -Xms1G -Xmx16G -XX:MaxPermSize=128m -XX:-UseGCOverheadLimit -cp "/online/sand/lib/client-api-1.0.0.jar:/online/sand/oap_pub/lib/*:/online/sand/oap/oap_dw/run/client_api/application.properties" team.online.client.api.MasterProcessor | tee -a client_api.log
我们使用 Sping 上下文以这种方式获取属性文件:
<util:properties id="app_props"
location="classpath*:/application.properties" />
然后以这种方式使用 appilcation.properties 文件中的属性(在许多不同的文件中):
@Value( "#{app_props[\"SERVICE_PATH_GET_METADATA\"]?:''}" )
private String metadataServicePath;
寻找一种方法将 .properties 文件保留在 jar 之外并保留在类路径中,以便 Spring 上下文找到该文件。
除了使用之外还有其他方法吗?我们需要将属性文件从 jar 中排除
class.getClassLoader( ).getResourceAsStream( "application.properties" );
提前致谢。
最佳答案
如果您使用基于 xml 的配置,请使用此选项
<context:property-placeholder location="classpath:application.properties"/>
然后它会从任何地方加载属性,只要它在类路径中而不是在 jar 中。您必须将其作为 $CLASSPATH:application.properties 包含在类路径中
对于基于注释的,@PropertySource("classpath:application.properties")
这里有一个样本
Java: read properties file using spring annotations
关于Java : How to include a . 属性文件位于 jar 之外,进入类路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45445531/