如何外部化 Web 应用程序的属性文件(war)?

How to externalize properties file for web application(war)?

我开发了一个具有 jsp 和 java 代码的网络应用程序。现在,我已将所有键值放入 env/lifecycle 特定属性文件(如 conf-dev.properties、conf-stg.properties、conf-prod.properties)。

我想将这些属性文件外部化,以便它可以放在 war 之外(不影响 war)。 现在 war 文件与属性文件紧密结合。如果我必须修改任何东西,我必须构建和制作 war 并部署。

我在部署服务器机器上的访问权限非常有限(只能访问一个我可以放置配置文件的文件夹)并且部署过程由 CI(jenkin 和自动化脚本)处理。

我在互联网上进行了探索,了解到我们可以使用 spring 实现此目的,想知道实现此目的的最佳方法是什么?

如果我理解你的问题,那么你可以使用 Class.getResourceAsStream(String) 链接的 Javadoc 说(部分)

This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).

外部化 env 特定属性的更好方法是使用 "user.home" 或 "user.dir"。

由于您正在使用 Spring,我想您已经在使用 PropertyPlaceholderConfigurer。如果不是,你应该 ;)

属性 文件的位置可以是任何可以解析为 spring Resource 的位置。这包括类路径、servletcontext 以及作为 URI 的文件引用(file:///...对于绝对路径)

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="${config.file.location}" />
</bean> 

谢谢@Martin F..

已解决:这是我使用的最后一个,它在 dev,stage Env 中运行良好。

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="false"/> <property name="order" value="1"/> <property name="locations"> <list> <value>classpath:conf-${cisco.life}.properties</value> <value>file:///${openshift.home}/data/conf-${cisco.life}.properties</value> <value>file:${openshift.home}/data/conf-${cisco.life}.properties</value> </list> </property> </bean>.

我在 openshift 中使用脚本操作挂钩在系统级别设置生命周期。

appname=echo $OPENSHIFT_APP_NAME case "$appname" in *dev)export JAVA_OPTS_EXT="${JAVA_OPTS_EXT} -Dcisco.life=dev"; echo "setting up env life dev for " $appname ;; *stage)export JAVA_OPTS_EXT="${JAVA_OPTS_EXT} -Dcisco.life=stg; echo "setting up env life as stg for " $appname.