【问题标题】:How to externalize properties file for web application(war)?如何外部化 Web 应用程序(战争)的属性文件?
【发布时间】:2015-10-22 02:14:27
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java spring tomcat7 openshift-cartridge


    【解决方案1】:

    当您使用 Spring 时,我想您已经使用了 PropertyPlaceholderConfigurer。如果不是,你应该;)

    属性文件的位置可以是任何可以解析为 springResource 的位置。这包括类路径、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> 
    

    【讨论】:

    • 是的,这种方法看起来不错……但我需要检查如何根据环境(dev、stg、prod)加载所有属性文件。在 openshift 中,我可以编写动作挂钩脚本来设置环境生命周期,例如用于开发服务器的 cisco.life=dev 和用于舞台服务器的 cisco.life=stg 等。
    • 例如可以将属性config.file.location声明为环境变量
    【解决方案2】:

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

    这个方法委托给这个对象的类加载器。如果此对象由引导类加载器加载,则该方法委托给ClassLoader.getSystemResourceAsStream(java.lang.String)

    【讨论】:

    • @EF ,谢谢你。是的,我已经使用该方法加载属性文件.. 寻找任何其他基于弹簧的方法。 String cisco_life = System.getProperty("cisco.life"); Properties configProp = new Properties(); InputStream in= Thread.currentThread().getContextClassLoader().getResourceAsStream("conf-"+cisco_life+".properties"); configProp.load(in);
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      感谢@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.

      【讨论】:

        猜你喜欢
        • 2010-09-24
        • 2018-03-10
        • 1970-01-01
        • 2015-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-06
        • 1970-01-01
        相关资源
        最近更新 更多