【问题标题】:propertyPlaceHolderConfigurer and environment variablepropertyPlaceHolderConfigurer 和环境变量
【发布时间】:2012-02-13 06:12:58
【问题描述】:

我正在尝试从环境变量加载属性文件,所以这是我尝试过的:

<bean id="propertyPlaceholderConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>

                <value>classpath:messages/application.properties</value>
                <value>file:${My_ENV_VAR}/*.properties</value>

            </list>
        </property>

        <property name="ignoreResourceNotFound" value="true" />
        <property name="searchSystemEnvironment" value="true" />
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />

    </bean>

我有一个名为My_ENV_VAR=C:\Program Files\My Folder\props.properties 的新环境变量 但是在停止和启动应用程序时,变量的值没有设置,有什么想法吗?

更新:要求

我想从文件系统上的外部属性文件中读取 applicationContext.xml 中的休眠属性(url、用户名、密码),其路径存储在环境变量中。 p>

【问题讨论】:

  • 在此处查看 Bozho 的答案:stackoverflow.com/questions/3965446/…
  • 你怎么知道没有设置?此外,您应该传递文件/文件模式,例如 file:${My_ENV_VAR}/*.properties 而不是目录。
  • 抱歉我更新了帖子,我知道它没有设置,因为在构建之后我看到了 applicationContext 并且我可以看到值 &lt;value&gt;file:${My_ENV_VAR}&lt;/value&gt; 没有改变。
  • 构建时不会被替换,spring会在运行时替换。如果您希望它在构建时被替换,请配置 maven 过滤或等效项。
  • 请问如何配置 maven 来做到这一点?

标签: spring spring-el


【解决方案1】:

您正在尝试使用PropertyPlaceholderConfigurer 创建PropertyPlaceholderConfigurer。那是先有鸡还是先有蛋的问题,不行!

尝试使用表达式语言(请参阅this section 以供参考),但在您的情况下,这很棘手,因为您想混合静态和动态内容。可能这样的事情会起作用:

<property name="locations"
  value="classpath:messages/application.properties,
  #{ T(java.lang.System).getenv('MY_ENV_VAR')}" />
  <!-- changed method name, it's getenv(), not getEnv() -->

【讨论】:

  • 对不起,我不明白,我希望属性占位符指向一个属性文件,它的值是从环境变量中读取的,这样的事情不可行?
  • 如果我正在尝试做的事情有其他解决方案,我会为需求添加更新。
  • @fresh_dev 问题是:您在创建 PropertyPlaceholderConfigurer 语法时使用它。
  • 它不起作用,我需要什么才能让 spring 表达式语言在它的 jar 旁边工作?我需要在beans xmlns 声明中添加任何内容吗?
  • 我使用的是 3.0.5.RELEASE 版本
【解决方案2】:

你应该使用这种方式:

首先声明spring bean

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

现在在WEB-INF/classes 目录中创建文件config.properties 并放入:

jboss.variable=${jboss.modules.dir}

注意:当我部署 JBoss 6 EAP 时,日志会显示:

jboss.modules.dir = C:\Java\jee-container\jboss-eap-6.1\modules

并在应用程序上下文文件中使用变量:

<bean id="nameOfBean"
    class="com.moeandjava.pusku.MySpringBean">
    <property name="path" value="${jboss.variable}" />
</bean>

对不起我的英语不好

【讨论】:

    猜你喜欢
    • 2012-05-06
    • 1970-01-01
    • 2015-09-16
    • 2019-08-21
    • 2014-07-03
    • 2016-04-30
    • 2014-04-22
    • 2013-03-03
    相关资源
    最近更新 更多