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



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

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

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

我在互联网上探索并了解到我们可以使用 Spring 实现这一目标,想知道实现这一目标的最佳方法是什么?

当你使用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> 

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

此方法委托给此对象的类装入器。如果此对象是由引导类装入器装入的,那么该方法将委托给 ClassLoader.getSystemResourceAsStream(java.lang.String)

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

谢谢@Martin F.。

解决:这是我使用的最后一个,它在开发阶段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=回显$OPENSHIFT_应用_名称 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

最新更新