【问题标题】:Is it possible to specify a context property placeholder at runtime是否可以在运行时指定上下文属性占位符
【发布时间】:2013-03-30 14:13:41
【问题描述】:

我有一个使用 spring 的独立 jar。我的 spring xml 中的配置使用了我在用 maven 编译时替换的占位符。示例弹簧配置:

<bean id="foo" class="package.Foo">
    <property name="host" value="${db.host}" />
</bean>

我想在运行时传入一个属性文件,而不是使用 maven 替换 ${db.host},例如

java -jar Application.jar productionDB.properties

这将允许我通过传入生产数据库属性文件或测试数据库属性文件在运行时切换数据库主机。

是否有可能做到这一点,或者有没有更好的方法来实现相同的目标?

【问题讨论】:

  • 使用数据源 xml 更改数据库可能是个好主意
  • 能分享一下applicationcontext的配置吗

标签: java spring properties


【解决方案1】:

您可以将您的属性文件指定为系统属性,例如:

java -jar Application.jar -DappConfig=/path/to/productionDB.properties

那么您应该能够在您的应用程序上下文中引用它:

<context:property-placeholder location="file:${appConfig}"/>

<bean id="foo" class="package.Foo">
    <property name="host" value="${db.host}" />
</bean>

【讨论】:

    【解决方案2】:

    您可以使用PropertyPlaceholderConfigurer 来使用.properties 文件来传递所需的变量。

    <bean id="placeholderConfig"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:productionDB.properties</value>
            </list>
        </property>
    </bean>
    

    您可以保留您的 bean 声明。属性将自动从productionDB.properties 文件中获取。

    【讨论】:

      【解决方案3】:

      有几个选项:

      1. 通过容器的 JNDI 设置资源并使用 Spring 的 &lt;jee:jndi-lookup/&gt;。
      2. 使用 Spring 的&lt;context:property-placeholder location="classpath:/myProps.properties" /&gt;。我更喜欢这种简写而不是“完整” bean 定义,因为 Spring 将自动使用正确的实现(PropertyPlaceholderConfigurer 用于 Spring PropertySourcesPlaceholderConfigurer 用于 Spring 3.1+)。使用此配置,您只需将myProps.properties 放在类路径的根目录下(例如${TOMCAT_HOME}/lib)。

      【讨论】:

        【解决方案4】:

        您可以使用 context:property-placeholder 传递值。所以你的设置是这样的:

        <context:property-placeholder location="file://opt/db.properties"/>
        

        然后当你连接你的 Foo 服务时,你可以在你的配置中使用属性名称,例如

        <bean id="foo" class="package.Foo">
           <property name="host" value="${db.host}" />
        </bean>
        

        然后为每个环境使用不同的文件集

        有关详细信息,请参阅spring 文档。

        【讨论】:

          猜你喜欢
          • 2013-12-06
          • 1970-01-01
          • 2012-08-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-29
          • 1970-01-01
          • 2011-07-12
          相关资源
          最近更新 更多